我现在有以下代码。基本上,这被称为获取所有摘要(在本例中为一些测试的摘要)。当前时区设置为UTC。我想基于本地时区获取所有数据。请告诉我任何想法吗?
public List<TestEntity> getAllTestSummary(String status) {
Timestamp timestampEnd = new Timestamp(System.currentTimeMillis());
long tenAgo = System.currentTimeMillis() - TEN_MINUTES;
Timestamp timestampStart = new Timestamp(tenAgo);
String TSPATTERN = "yyyy-MM-dd HH:mm:ss";
DateFormat df = DateFormat.getDateTimeInstance();
df = new SimpleDateFormat(TSPATTERN);
df.setTimeZone(TimeZone.getTimeZone("UTC"));
timestampStart = Timestamp.valueOf(df.format(timestampStart).toString());
timestampEnd = Timestamp.valueOf(df.format(timestampEnd).toString());
return testRepository.findByStatusIgnoreCase(status);
}
我尝试使用joda
,但未获得所需的输出。
日期没有时区,并且内部存储在UTC中。仅当格式化日期时,时区校正才适用。使用DateFormat时,它默认为运行时的JVM的时区。根据需要使用setTimeZone进行更改。
DateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"))
;
Date date = utcFormat.parse("2012-08-15T22:56:02.038Z");
DateFormat pstFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
pstFormat.setTimeZone(TimeZone.getTimeZone("PST"));
System.out.println(pstFormat.format(date));
此打印
2012-08-15T15:56:02.038
注意我以PST格式省略了'Z'
,因为它表示UTC。如果仅使用Z,则输出为2012-08-15T15:56:02.038-0700
更新1:
[您甚至可以使用Joda-Time,或者在Java 8中使用由JSR 310定义并由@Ole V.V建议的Joda-Time启发的new java.time.*类。