繁体   English   中英

Java日历日期操作问题

[英]Java Calendar date manipulation issue

我尝试以下列格式获取当前日期/时间,

SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z"); 
// should display something similar to  2001.07.04 AD at 12:08:56 PDT
Calendar calendar = Calendar.getInstance();
calendar.set(2009, 2, 4, 10, 22, 44);
format.format( calendar.getTime() );
System.out.println(calendar.getTime());

但它显示为2009年3月4日星期三10:22:44 IST 2009。

第二个问题是我想看到设定时间的毫秒值。

System.out.println(calendar.getTimeInMillis());

但它总是返回当前时间毫秒值而不是我之前设置的时间。

我在这里失踪了什么?

SimpleDateFormat#format(Object)方法返回格式化的String ,它不会影响Calendar#getTime()方法返回的方式。 为此你应该做一个:

System.out.println(format.format(calendar.getTime()));

我看到的第一个问题是format.format(calendar.getTime()); 返回一个String,实际上并没有改变Calendar的格式。 您将要使用System.out.println(format.format(calendar.getTime()));替换最后两行System.out.println(format.format(calendar.getTime())); 使用您指定的格式实际打印出日期(假设您的SimpleDateFormat有效,但它看起来很快就能看到)。

不幸的是,不确定你遇到的第二个问题,但我有一个地方可供你开始。 我不喜欢getTime()getTimeInMillis()的Javadocs的措辞。 getTime()方法返回“表示此Calendar的时间值的Date对象”,而getTimeInMillis()返回“当前时间为UTC时间的毫秒”。 对我来说,措辞的不同意味着getTimeInMillis()不使用Calendar对象指定的日期,即使它是一个实例方法。 尝试System.out.println(calendar.getTime().getTime()); 为了在Calendar的Date表示上调用getTime()方法,该文档返回1970年1月1日到Date对象表示的日期之间的时间(以毫秒为单位)。

对于问题的第二部分,您应该调用Calendar.get(Calendar.MILLISECONDS)来检索日历对象的毫秒字段。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM