日期格式化

public class DateUtils {

    public final static String DATE_PATTERN_YYYY_MM_DD = "yyyy-MM-dd";
    public final static String DATE_PATTERN_YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm";
    public final static String DATE_PATTERN_YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
    public final static String DATE_PATTERN_HH_MM_SS = "HH:mm:ss";
    public final static String DATE_PATTERN_HH_MM = "HH:mm";
    public final static String DATE_PATTERN_YY_M_D = "yy/M/d";

    /**
     * calendar to string
     *
     * @param calendar Calendar
     * @return String
     */
    public static String calendarToStrByPattern(Calendar calendar, String pattern) {
        SimpleDateFormat format1 = new SimpleDateFormat(pattern);
        return format1.format(calendar.getTime());
    }

    /**
     * 匹配pattern获得时间,若无法解析抛出异常
     *
     * @param dateTimeStr String
     * @param patternStr  String
     * @return Calendar
     * @throws IllegalArgumentException
     */
    public static Calendar getCalendarByPattern(String dateTimeStr, String patternStr) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(patternStr, Locale.US);
            sdf.setLenient(false);
            Date d = sdf.parse(dateTimeStr);
            Calendar c = Calendar.getInstance();
            c.setLenient(false);
            c.setTimeInMillis(d.getTime());
            return c;
        } catch (Exception e) {
            throw new IllegalArgumentException(e);
        }
    }

    public static int getIntervalDays(Calendar from, Calendar to) {
        long dayMillis = 24 * 60 * 60 * 1000;
        int betweenDays;
        Calendar c1 = Calendar.getInstance();
        c1.set(from.get(Calendar.YEAR), from.get(Calendar.MONTH), from.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        c1.set(Calendar.MILLISECOND, 0);
        Calendar c2 = Calendar.getInstance();
        c2.set(to.get(Calendar.YEAR), to.get(Calendar.MONTH), to.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        c2.set(Calendar.MILLISECOND, 0);
        long a = c1.getTimeInMillis();
        long b = c2.getTimeInMillis();
        long bt = Math.abs(a - b);
        betweenDays = (int)(bt / dayMillis);
        return betweenDays;
    }

    public static int getIntervalDays(String startdate, String enddate, String pattern) {
        int betweenDays = 0;
        if (startdate == null || enddate == null) {
            return betweenDays;
        }

        Calendar d1 = getCalendarByPattern(startdate, pattern);
        Calendar d2 = getCalendarByPattern(enddate, pattern);

        return getIntervalDays(d1, d2);
    }

    /**
     * @param time yyyy-MM-dd
     * @return 毫秒
     * @since 2015612     */
    public static long getStringToDate(String time) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        try {
            date = sf.parse(time);
        } catch (ParseException e) {

            LogUtil.e(e);
        }
        return date.getTime();
    }

    /**
     * @param time 毫秒
     * @return yyyy-MM-dd
     * @since 2015612     */
    public static String getDateToString(long time) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        Date d = new Date(time);
        return sf.format(d);
    }

    public static String formatElapsedTime(long elapsedSeconds) {
        long hours = 0;
        long minutes = 0;
        long seconds;
        if (elapsedSeconds >= 3600) {
            hours = elapsedSeconds / 3600;
            elapsedSeconds -= hours * 3600;
        }
        if (elapsedSeconds >= 60) {
            minutes = elapsedSeconds / 60;
            elapsedSeconds -= minutes * 60;
        }
        seconds = elapsedSeconds;

        StringBuilder sb = new StringBuilder(8);

        Formatter f = null;
        try {
            f = new Formatter(sb, Locale.getDefault());
            if (hours > 0) {
                return f.format("%d:%02d:%02d", hours, minutes, seconds).toString();
            } else {
                return f.format("%02d:%02d", minutes, seconds).toString();
            }
        } finally {
            if (f != null) {
                f.close();
            }
        }
    }

    /**
     * 把时间毫秒值转换为默认的日期格式。<br>
     * 例如中国: 2015612     *
     * @param milliseconds 毫秒
     * @return 默认的日期格式
     * @since 2015612     */
    public static String formatDateDefault(long milliseconds) {
        DateFormat format = SimpleDateFormat.getDateInstance();
        return format.format(new Date(milliseconds));
    }

    public static String formatDateDefault(long milliseconds, Locale locale) {
        DateFormat format = SimpleDateFormat.getDateInstance(DateFormat.YEAR_FIELD, locale);
        return format.format(new Date(milliseconds));
    }

    /**
     * 判断时差是否超过一小时
     *
     * @param currentTime 现在的时间
     * @param lastTime    之前的时间
     * @return true - 超过一个小时; false - 不超过一个小时.
     */
    public static boolean isHourPassed(long currentTime, long lastTime) {
        return currentTime - lastTime >= 3600000;
    }

    public static String getHMSData(long milliseconds) {
        SimpleDateFormat sf = new SimpleDateFormat(DATE_PATTERN_HH_MM_SS);
        Date d = new Date(milliseconds);
        return sf.format(d);
    }

    public static String getHMData(long milliseconds) {
        SimpleDateFormat sf = new SimpleDateFormat(DATE_PATTERN_HH_MM);
        Date d = new Date(milliseconds);
        return sf.format(d);
    }

    /**
     * 获取友好的时间格式
     * <p/>
     * 5分钟内:现在 <br/>
     * 1小时内:刚刚 <br/>
     * 1小时前:HH:mm <br/>
     * 0点前:昨天 <br/>
     * 7天内:星期W <br/>
     * 其他:yy/M/d <br/>
     *
     * @param context    Context
     * @param timeMillis 时间
     * @return 友好的时间格式
     */
    public static String getFriendlyTime(Context context, long timeMillis) {
        if (context == null)
            return null;

        long dTime = System.currentTimeMillis() - timeMillis;
        // 未来
        if (dTime < 0)
            return getFormatData(timeMillis, DATE_PATTERN_YY_M_D);
        // 5分钟内
        if (dTime < 5 * 60 * 1000)
            return context.getString(R.string.date_now);
        // 1小时内
        if (dTime < 60 * 60 * 1000)
            return context.getString(R.string.date_just_now);

        // 判断今天/昨天/本周/更早
        Calendar last = Calendar.getInstance();
        last.setFirstDayOfWeek(Calendar.MONDAY);
        last.setTimeInMillis(timeMillis);
        // 今天
        Calendar temp = Calendar.getInstance();
        temp.setFirstDayOfWeek(Calendar.MONDAY);
        temp.set(Calendar.MILLISECOND, 0);
        temp.set(Calendar.SECOND, 0);
        temp.set(Calendar.MINUTE, 0);
        temp.set(Calendar.HOUR_OF_DAY, 0);
        if (!last.before(temp))
            return getHMData(timeMillis);
        // 昨天
        temp.add(Calendar.DAY_OF_YEAR, -1);
        if (!last.before(temp))
            return context.getString(R.string.date_yesterday);
        // 一周内
        temp.add(Calendar.DAY_OF_YEAR, -5);
        if (!last.before(temp)) {
            int week = last.get(Calendar.DAY_OF_WEEK) - 1;
            return context.getResources().getStringArray(R.array.week_name)[week % 7];
        }
        return getFormatData(timeMillis, DATE_PATTERN_YY_M_D);
    }

    /**
     * 格式化时间
     *
     * @param timeMillis 时间毫秒值.
     * @param pattern    格式, 可以为null使用默认的格式 yyyy-MM-dd HH:mm:ss
     * @return 格式化时间
     */
    public static String getFormatData(long timeMillis, String pattern) {
        if (TextUtils.isEmpty(pattern))
            pattern = DATE_PATTERN_YYYY_MM_DD_HH_MM_SS;
        SimpleDateFormat formatter = new SimpleDateFormat(pattern);
        Date curDate = new Date(timeMillis);
        return formatter.format(curDate);
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值