我从外部组件中单独获取时间和时间的时区。 时间的格式为“MMM dd yyyy hh:mma”。例如:2014 年 10 月 31 日 12:54PM,此时的时区是单独接收的。
在保存到数据库之前,我需要将此时间标准化为 EST 时区。我尝试了Calendar(我不认为这可以用java Date来完成),但是输出有相当大的不一致,然后经过一些谷歌搜索,认为Joda有更好的支持并切换到它。但我收到以下异常。
String clientTimeZone = "America/New_York";
String value = "Nov 25 2014 2:18PM";
DateTimeFormatter df = DateTimeFormat.forPattern("MMM dd yyyy hh:mma");//.withLocale(Locale.ENGLISH);
DateTime temp = df.withZone(DateTimeZone.forID(clientTimeZone)).withOffsetParsed().parseDateTime(value);
DateTime date = temp.withZone(DateTimeZone.forID("America/New_York"));
Timestamp ts = new Timestamp(date.getMillis());
Date d = new Date(ts.getTime());
System.out.println(d.toString());
我得到了:
java.lang.IllegalArgumentException:格式无效:“2014 年 11 月 25 日 2:18PM”在“2:18PM”时格式错误 在 org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:899) 在 LearnJoda.main(LearnJoda.java:34)
知道可能出现什么问题吗?
最佳答案
编辑:在OP提供更多信息后,答案已略有改变。
您可以使用以下模式(您定义的)。
"MMM dd yyyy hh:mma"
但是,由于您的输入字符串根据是 2 位数小时还是一位数小时而有所不同,因此我建议您使用 String.replace
方法(如建议的那样)对值进行预处理在这个 answer )。
@Test
public void test() throws JsonProcessingException {
final String value1 = "Nov 24 2014 2:40PM"; // Double space
final String value2 = "Nov 24 2014 11:40PM"; // Single space
// Set up a test time zone
final ZoneId clientTimeZone = ZoneId.systemDefault();
// Create the formatter (as previously)
DateTimeFormatter df = DateTimeFormat.forPattern("MMM dd yyyy hh:mma");
DateTime temp1 =
df.withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone(clientTimeZone)))
.withOffsetParsed()
.parseDateTime(value1.replace(" ", " ")); // replace double space with single space
DateTime temp2 =
df.withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone(clientTimeZone)))
.withOffsetParsed()
.parseDateTime(value2.replace(" ", " ")); // always replace to be sre
DateTime date1 = temp1.toDateTime(DateTimeZone.forTimeZone(TimeZone.getTimeZone("America/New_York")));
DateTime date2 = temp2.toDateTime(DateTimeZone.forTimeZone(TimeZone.getTimeZone("America/New_York")));
Timestamp ts1 = new Timestamp(date1.getMillis());
Timestamp ts2 = new Timestamp(date2.getMillis());
}
如果您使用 Java 8,也可以跳过 Joda,而使用 java.time
包中的新 Java 8 时间和日期函数。例如
DateTimeFormatter df = DateTimeFormatter.ofPattern("MMM dd yyyy h:ma");
关于java - 将日期时间转换为不同的时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27691073/