我有一个包含日期和时间信息的 Java Date 对象,例如 2010-11-11T09:30:47。我想编写一个方法来将此 Date 对象转换为以下格式。 “yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
我编写了以下代码。
private Calender getValue(Date dateObject) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
String timestamp = formatter.format(dateObject);
System.out.println("Created GMT cal with date [" + timestamp + "]");
}
当我运行程序时,它正在打印
Created GMT cal with date [2010-11-11T04:00:47.000Z]
我给出的是“2010-11-11T09:30:47”,我的时间是09:30:47。它打印的是“04:00:47”。
为什么时间从 9.30 变为 4.00?
我需要做什么才能获得与我付出的时间相同的时间。像2010-11-11T09:30:47.000Z
非常感谢。
最佳答案
您只需删除以下行
formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
因为您将时区设置为 GMT,而您的时区是 GMT + 5.30。这就是为什么当您将时间设置为 9.30 时,您将得到 9.30 - 5.30 = 4.00。
您可以使用以下代码:
private void getValue(Date dateObject)
{
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
String timestamp = formatter.format(dateObject);
System.out.println("Created GMT cal with date [" + timestamp + "]");
}
关于java - 以我给出的格式获取日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16165744/