Java 日期类常用写法小结

2015/04/03 Java

Date 和 Calendar 转 String

借助 SimpleDateFormat 类的 format 方法,Calendar.getTime() 返回 Date,最终 Calendar 也是转化为 Date 后转 String。

// see SimpleDateFormat in Java API
String format = new String("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);

// Date
String strDate = sdf.format(new Date());

Calendar cal = Calendar.getInstance();
// Calendar
String strCalendar = sdf.format(cal.getTime());

String 转 Date、Calendar

String strDate = "2015-04-04 00:33:00";
Date date = null;
Calendar cal = Calendar.getInstance();
try {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
    date = sdf.parse(strDate);
    cal.setTime(date);
} catch (Exception e) {
    e.printStackTrace();
}

设置 Calendar 到某年某月某日

注意点:

  • Month 要设为比实际小 1。
  • 除显式设置的几个字段外,其它字段之前的值不变;如果不是期待的,可以先调用 clear() 清除。
Calendar cal = Calendar.getInstance();
// set to 2015-03-01
cal.set(2015, 3 - 1, 1);

复制 Calendar

Calendar calDst = (Calendar)calSrc.clone();

求本周、上周、下周的起始时间

做了一个工具类来处理此事(注意:这里计算的一周是从周一到周日,如果要算周天到周六,把获取本周一时括号里的 +1 去掉):

static class DateCalcUtil {
    public static final int GET_PREVIOUS_MONDAY = 0;
    public static final int GET_PREVIOUS_SUNDAY = 1;
    public static final int GET_THIS_MONDAY = 2;
    public static final int GET_THIS_SUNDAY = 3;
    public static final int GET_NEXT_MONDAY = 4;
    public static final int GET_NEXT_SUNDAY = 5;

    public static Calendar calc(Calendar base, int calcType) {
        // 获取这一周开始基准
        int min = base.getActualMinimum(Calendar.DAY_OF_WEEK);
        // 获取当天在这一周内天数
        int current = base.get(Calendar.DAY_OF_WEEK);
        Calendar calendar = (Calendar)base.clone();

        // 获取本周一
        int nCount = (current == min) ? -6 : (min - current + 1);

        switch (calcType) {
            case GET_PREVIOUS_MONDAY:
                nCount -= 7;
                break;

            case GET_PREVIOUS_SUNDAY:
                nCount -= 1;
                break;

            case GET_THIS_MONDAY:
                break;

            case GET_THIS_SUNDAY:
                nCount += 6;
                break;

            case GET_NEXT_MONDAY:
                nCount += 7;
                break;

            case GET_NEXT_SUNDAY:
                nCount += 13;
                break;

            default:
                break;
        }

        calendar.add(Calendar.DAY_OF_WEEK, nCount);

        return calendar;
    }
}

使用示例如下:

// 今天
Calendar base = Calendar.getInstance();

// 本周
Calendar thisMonday = DateCalcUtil.calc(base, DateCalcUtil.GET_THIS_MONDAY);
Calendar thisSunday = DateCalcUtil.calc(base, DateCalcUtil.GET_THIS_SUNDAY);

// 下周
Calendar nextMonday = DateCalcUtil.calc(base, DateCalcUtil.GET_NEXT_MONDAY);
Calendar nextSunday = DateCalcUtil.calc(base, DateCalcUtil.GET_NEXT_SUNDAY);

// 上周
Calendar previousMonday = DateCalcUtil.calc(base, DateCalcUtil.GET_PREVIOUS_MONDAY);
Calendar previousSunday = DateCalcUtil.calc(base, DateCalcUtil.GET_PREVIOUS_SUNDAY);

获取两个日期相差天数

注意点:

  • getTimeInMillis 返回的是 0 时区时间,所以有可能把你的时间加减了几个小时,造成计算天数有误,这种方法必须考虑时区因素再运算。
long daysCount1 = (calendar1.getTimeInMillis() + calendar1.get(Calendar.ZONE_OFFSET))
    / (24 * 3600 * 1000);
long daysCount2 = (calendar2.getTimeInMillis() + calendar2.get(Calendar.ZONE_OFFSET))
    / (24 * 3600 * 1000);
long dayDiffer = daysCount1 - daysCount2;
Show Disqus Comments

Search

    欢迎关注我的微信公众号

    闷骚的程序员

    Table of Contents