我一直在尝试使用以下代码将服务器的日期和时间转换为用户的日期和时间
@Test
public void playingWithJodaTime() {
LocalDateTime localDateTime = new LocalDateTime();
System.out.println("server localDateTime : "
+ localDateTime.toDateTime(DateTimeZone.getDefault()).toDate());
System.out.println("user's localDateTime : "
+ localDateTime.toDateTime(DateTimeZone.forID("Asia/Jakarta"))
.toDate());
}
Run Code Online (Sandbox Code Playgroud)
印刷结果
server localDateTime : Tue Dec 17 00:04:29 SGT 2013
user's localDateTime : Tue Dec 17 01:04:29 SGT 2013
Run Code Online (Sandbox Code Playgroud)
但是,由于服务器时区是(UTC+08:00) Kuala Lumpur, Singapore用户的,因此打印结果与我的预期不符(UTC+07:00) Bangkok, Hanoi, Jakarta.
我在这做错了什么?
您正在将DateTime转换为Java Date(为什么?).
java.util.Date使用默认JVM的时区
因此,您在此转换时错过了时区.
此示例按预期工作:
LocalDateTime localDateTime = new LocalDateTime();
System.out.println("server localDateTime : "
+ localDateTime.toDateTime(DateTimeZone.getDefault()));
System.out.println("user's localDateTime : "
+ localDateTime.toDateTime(DateTimeZone.forID("Asia/Jakarta")));
Run Code Online (Sandbox Code Playgroud)
如果你想将joda DateTime转换为其他东西,则将其转换为Calendar
LocalDateTime localDateTime = new LocalDateTime();
System.out.println("server localDateTime : "
+ localDateTime.toDateTime(DateTimeZone.getDefault()).toGregorianCalendar());
System.out.println("user's localDateTime : "
+ localDateTime.toDateTime(DateTimeZone.forID("Asia/Jakarta")).toGregorianCalendar());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13256 次 |
| 最近记录: |