【问题标题】:how to get a timestamp of another timezone in java or JODA如何在 java 或 JODA 中获取另一个时区的时间戳
【发布时间】:2012-11-12 09:44:11
【问题描述】:

我想从不同的时区获取当前时间(现在)。

例如使用 joda 日期时间库,

我可以像使用 JODA 日期时间一样获取澳大利亚时区

DateTime zoned = new DateTime(DateTimeZone.forID("Australia/Melbourne"));

及其当前时间使用

DateTime.now(DateTimeZone.forID("Australia/Melbourne"));

如果我想将此 DateTime 对象转换为 java.sql.Timestamp 对象

,我必须得到它的毫秒使用

DateTime 类的getMillis 方法实例化新的时间戳对象

Timestamp zonedStamp = new TimeStamp(zoned.getMillis());

因此,每次自纪元时间以来经过的毫秒数在逻辑上对于每个时区都是相同的。

我的问题是如何获取澳大利亚时区的当前时间以获取分区时间戳对象。

谢谢你 米希尔·帕雷赫

【问题讨论】:

  • 您的意思是Timestamp 的值应该等于澳大利亚当前时间吗?

标签: java jodatime


【解决方案1】:

如果您想要一个具有澳大利亚时区等效时间值Timestamp 对象,请尝试以下操作:

    Date currentTime = new Date();
    DateFormat ausFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
    ausFormat.setTimeZone(TimeZone.getTimeZone("Australia/Melbourne"));

    //get the time string in australian timezone
    String ausTime  = ausFormat.format(currentTime);

    //Convert the above time string in local date object
    DateFormat currentFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
    //optional: set the timezone as Asia/Calcutta
    currentFormat.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
    Date ausTimeInLocal = currentFormat.parse(ausTime);

    //get the time stamp object using above date object
    Timestamp ausTimeStampInLocal = new Timestamp(ausTimeInLocal.getTime());

【讨论】:

  • 这仍然会在本地/默认时区提供时间戳。这是因为 DatFormat.format() 和 parse() 从配置的时区 (DateFormat.setTimeZone()) 输出和读取到本地时区。当您想处理时区时,java.util.Date 不是正确的类。请改用 java.util.Calendar。话虽如此,唯一的解决方案是切换您的默认时区(TimeZone.setDefaultZone()),这可能不利于中间过程。我认为应该只在启动时配置时区。
  • 谢谢约根德拉。 sgp15 先生,您是对的,但是尽管您从一开始就设置了不同的时区,但无论您使用 JODA、UTIL 还是 Calendar 类,毫秒在逻辑上都是相同的,我关心的是获得不同时区时间的毫秒数,这样我就可以基于 it 实例化 Timestamp。感谢 oyur cmets。
  • 你好 Yogendra 我注意到上面的代码给了我 4 小时的差异,实际上印度标准时间和墨尔本时间有 4.30 小时的差异。你能告诉我为什么吗?
  • @Mihir:尝试设置适当的时区。此外,您可能还想在currentFormat 中设置时区。
  • @Yogendra 时区合适。它与您在示例中使用的相同。
猜你喜欢
  • 2012-06-20
  • 2015-05-06
  • 1970-01-01
  • 1970-01-01
  • 2014-07-21
  • 1970-01-01
  • 2022-07-17
  • 2012-08-03
  • 1970-01-01
相关资源
最近更新 更多