我在使用 Joda Time 库获取本地时间时遇到问题。这是我正在尝试做的一个简单示例。
package simple;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalDateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class TestJodaLocalTime {
public static void main(String[] args) {
//time in UTC standard
DateTime processingDate = DateTime.now();
//local time
LocalDateTime localDateTime = processingDate.
withZone(DateTimeZone.getDefault()).toLocalDateTime();
DateTimeFormatter fmtDate = DateTimeFormat.forPattern("dd/MM/yyyy");
DateTimeFormatter fmtHour = DateTimeFormat.forPattern("HH:mm:ss");
System.out.println("Date: " + fmtDate.print(processingDate));
System.out.println("Time: " + fmtHour.withZone(DateTimeZone.UTC).
print(processingDate));
System.out.println("Local date: " + fmtDate.print(localDateTime));
System.out.println("Local time: " + fmtHour.print(localDateTime));
}
}
我原以为,在打印本地时间时,我会得到应用程序运行所在时区的时间,但我得到的时间与 UTC DateTime 相同。
Date: 06/12/2012
Time: 12:55:49
Local date: 06/12/2012
Local time: 12:55:49
我在这里错过了什么?
最佳答案
此评论可能是问题的一部分:
//time in UTC standard
DateTime processingDate = DateTime.now();
否,DateTime.now()
返回默认时区的当前时间。因此,当您稍后使用 withZone(DateTimeZone.getDefault())
时,这是一个空操作。
但是,我仍然期望 fmtHour.withZone(DateTimeZone.UTC).print(processingDate)
转换为 UTC。
确实,这就是我手动将默认时区设置为 UTC 以外的时区时得到的结果:
import org.joda.time.*;
import org.joda.time.format.*;
public class Test {
public static void main(String[] args) {
DateTimeZone pacific = DateTimeZone.forID("America/Los_Angeles");
DateTimeZone.setDefault(pacific);
DateTime processingDate = DateTime.now();
//local time
LocalDateTime localDateTime = processingDate.
withZone(DateTimeZone.getDefault()).toLocalDateTime();
DateTimeFormatter fmtDate = DateTimeFormat.forPattern("dd/MM/yyyy");
DateTimeFormatter fmtHour = DateTimeFormat.forPattern("HH:mm:ss");
System.out.println("Date: " + fmtDate.print(processingDate));
System.out.println("Time: " + fmtHour.withZone(DateTimeZone.UTC).
print(processingDate));
System.out.println("Local date: " + fmtDate.print(localDateTime));
System.out.println("Local time: " + fmtHour.print(localDateTime));
}
}
输出:
Date: 06/12/2012
Time: 13:19:35
Local date: 06/12/2012
Local time: 05:19:35
您确定问题不仅仅在于您的默认时区是 UTC 吗?
关于java - 从 DateTime 对象获取 LocalDateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13744211/