Java中的GregorianCalendar类 [英] GregorianCalendar Class in Java

查看:47
本文介绍了Java中的GregorianCalendar类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取其他时区的当前时间.我为此使用了此代码:

I am trying to get current time in other time zone. I used this code for this:

GregorianCalendar calender = new         
GregorianCalendar(TimeZone.getTimeZone("Asia/Bangkok"));
    System.out.println(calender.getTime());

但是,当我运行此代码时,由于本地计算机中的时间位于CET中,因此该代码提供了CET中的当前时间.我很困惑.那么为什么要在构造函数中提供一个TimeZone呢?

But, when I am running this code, this code provides the current time in CET as the time in my local machine is in CET. I am confused. Then why there is scope to provide a TimeZone in constructor?

推荐答案

啊,Java日期/时间API的乐趣...

Ahh, the joys of the Java Date/Time API ...

您想要的(除了更好的API,例如Joda Time)是 DateFormat .它可以在您指定的时区中打印日期.您不需要 Calendar .

What you want (aside from a better API, such as Joda Time) is a DateFormat. It can print dates in a time zone you specify. You don't need Calendar for that.

dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Bangkok"));
dateFormat.format(new Date());


日历用于时间操纵和计算.例如将时间设置为10 AM".然后,它需要时区.


Calendar is for time manipulations and calculations. For example "set the time to 10 AM". Then it needs the timezone.

完成这些计算后,您可以调用 calendar.getTime()并返回 Date .

When you are done with these calculations, then you can get the result by calling calendar.getTime() which returns a Date.

Date 本质上是通用时间戳(自1970年以来以毫秒为单位,没有附加或相关的时区信息).如果您在 Date 上调用 toString ,它将仅在您的默认时区打印一些内容.要进行更多控制,请使用 DateFormat .

A Date is essentially a universal timestamp (in milliseconds since 1970, with no timezone information attached or relevant). If you call toString on a Date it will just print something in your default timezone. For more control, use DateFormat.

这篇关于Java中的GregorianCalendar类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆