所以我一直在研究一个简单的小方法,它将返回一个 String
作为 Calendar
对象。
这是我所拥有的:
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.ENGLISH);
try {
cal.setTime(sdf.parse(this.getCreated_at()));
}
catch (ParseException e) {
e.printStackTrace();
}
return cal;
现在假设从 this.getCreated_at())
获取的 String
始终采用所需的格式,理论上,这应该可以完美工作。
只有一个小问题。
假设 this.getCreated_at())
返回 Mon Feb 10 18:52:54 +0000 2014
。应该不会有问题吧?格式正确,一切都正确。
但是,当我有主要方法时,请执行以下操作:
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy");
System.out.println(sdf.format(... ... ....stringToCalendar().getTime()));
它给了我以下输出:
ma feb 10 19:52:54 +0100 2014
您可能已经注意到,我的问题是,首先,时间不对。增加了一个小时。
其次,它将文本字段 Mon
和 Feb
翻译为 ma
和 feb
(挪威语翻译) ,我现在编码的地方。
我需要将时间作为 Calendar
对象返回给我,其方式与从 this.getCreated_at())
字符串获取的方式完全相同。
我做错了什么?
谁能帮帮我吗?
顺便说一句,我来自挪威。这是 +01:00 标准偏移。
最佳答案
My problem, as you may have noticed, is that firstly, the time is wrong. It's added an hour.
不,还没有。并不真地。它显示的时间完全相同,但采用您本地的时区。不幸的是,您无法轻松确定原始时区,因为 DateFormat.parse
返回一个 Date
,其中不包含任何时区信息。 (在这种情况下,您实际上并不知道完整的时区 - 您只知道 UTC 偏移量,这并不完全相同。)
编辑:正如乔尼的回答所述,似乎 DateFormat.parse
确实保留了格式日历中的原始信息;您不需要时区,但可以使用 Calendar
对象中存储的偏移量。就我个人而言,这似乎是一个我不想依赖的实现细节(特别是当您最终得到一个偏移量,该偏移量不一定受同一日历对象中的时区支持!)但是您如果你真的想要的话,可以破坏它。
Secondly, it's translated the text fields Mon and Feb into ma and feb which are translations to Norwegian, the place from where I'm coding now.
这是因为您的 SimpleDateFormat
使用的是默认区域设置。
您可以非常轻松地修复此部分:
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy",
Locale.ENGLISH);
如果您知道要使用哪个时区,也可以在 SimpleDateFormat
上指定。否则,你的日子会比较难过。
我建议您开始使用 Joda Time 。这样,您可以将值解析为 DateTime
,它“知道”它所在的时区 - 因此您可以根据需要重新格式化它,保留相关的时区信息。
示例 Joda 时间代码:
import java.util.*;
import org.joda.time.*;
import org.joda.time.format.*;
class Test {
public static void main(String[] args) {
DateTimeFormatter format = DateTimeFormat
.forPattern("EEE MMM dd HH:mm:ss Z yyyy")
.withLocale(Locale.ENGLISH);
String input = "Mon Feb 10 18:52:54 +0000 2014";
DateTime value = format.parseDateTime(input);
System.out.println(format.print(value));
}
}
关于java - Java中的日历对象返回错误的时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21685666/