如何在java或JODA中获取另一个时区的时间戳
我想从不同的时区获取当前时间(现在) 例如,使用joda datetime库 我可以像使用JODA datetime一样获得澳大利亚时区如何在java或JODA中获取另一个时区的时间戳,java,jodatime,Java,Jodatime,我想从不同的时区获取当前时间(现在) 例如,使用joda datetime库 我可以像使用JODA datetime一样获得澳大利亚时区 DateTime zoned = new DateTime(DateTimeZone.forID("Australia/Melbourne")); 及其当前使用时间 DateTime.now(DateTimeZone.forID("Australia/Melbourne")); 如果要将此DateTime对象转换为java.sql.Timestamp对象
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());
因此,从历元时间开始,每次经过的毫秒在逻辑上对于每个时区都是相同的
我的问题是如何获取Autralian时区的当前时间以获取分区时间戳对象。
多谢各位
Mihir Parekh如果您想要一个具有澳大利亚时区等效时间值的
时间戳
对象,请尝试以下操作:
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()),这可能不利于中间进程。我认为只有在启动时才应该配置时区。谢谢Yogendra。sgp15先生,你说得对,但尽管你从一开始就设置了不同的时区,但从逻辑上讲,无论你使用JODA、UTIL还是Calendar类,毫秒数都是相同的,我关心的是获取不同时区的毫秒时间,这样我就可以基于它实例化时间戳。感谢oyur的评论。你好,Yogendra,我注意到上面的代码给了我4小时的差值,实际上印度标准时间和墨尔本时间的差值是4.30小时。你能告诉我为什么吗?@Mihir:试着设置合适的时区。此外,您可能还需要在currentFormat
中设置时区。@Yogendra时区是合适的。这与您在示例中使用的相同。