Java Calendar 时间“误差”问题

28 篇文章 1 订阅
22 篇文章 0 订阅

使用Calendar计算日期需要注意的问题

1. Calendar.getInstance()方法

相关源码:

Gets a calendar using the default time zone and locale. The Calendar returned is based on the current time in the default time zone with the default FORMAT locale.

Returns: a Calendar.

public static Calendar getInstance(){
    return createCalendar(TimeZone.getDefault(),
                          Locale.getDefault(Locale.Category.FORMAT));
}

getInstence() 方法基于方法执行瞬间的时间创建 Calendar 实例。所以连续两次调用 getInstance()方法返回的 Calendar 对象代表是时间不相同的。

通过执行以下代码可以明显的查看到这种区别:

public class Main {
    public static void main(String[] args) {

        Calendar calendar1 = Calendar.getInstance();
        Calendar calendar2 = Calendar.getInstance();

        System.out.println("日期1:" + calendar1.getTimeInMillis() + "(毫秒)");
        System.out.println("日期2:" + calendar2.getTimeInMillis() + "(毫秒)");
    }
}

我执行上面这段代码时的执行结果:

日期1:1598523874732(毫秒)
日期2:1598523874755(毫秒)

Process finished with exit code 0

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值