我有以下代码:
public static void main(String[] args) {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//get current date time with Date()
Date date = new Date();
String currentDate = dateFormat.format(date);
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
System.out.println(sdf.format(getSomeDate(currentDate,TimeZone.getTimeZone("Asia/Omsk"))));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Date getSomeDate(final String str, final TimeZone tz) throws ParseException {
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
sdf.setTimeZone(tz);
return sdf.parse(str);
}
现在的问题是,如果我使用所需的时区(即“美国/芝加哥”),则会得到完全错误的时间。当前时间是+6,而不是-6。
所以我将如何解决这个问题,因为现在我必须将格林尼治标准时间+ 6设为一个时区,以获取程序的正确时间和日期。
而且,Java是否会自动合并DST设置?由于世界各地的人们都在使用此时间,因此DST时间不同,因此很难保持正确的时间。
问题,我想是您在getSomeDate()方法中为SimpleDateFormat设置了TimeZone一次。尝试对SimpleDateFormat的所有实例执行此操作。
现代方法使用java.time类。您正在使用可怕的日期时间类,这些类在几年前由于采用JSR 310而过时。
String input = "2020-01-23 15:00:00" ;
此类输入,因为它缺少时区或UTC偏移量的指示符。因此,我们必须将其解析为LocalDateTime
。这样的对象确实代表了一个时刻,因为我们不知道您是指东京,图卢兹还是托莱多的下午3点-彼此不同的时刻相隔数小时。 LocalDateTime ldt = LocalDateTime.parse( input.replace( " " , "T" ) ) ;
您似乎可以确定此日期和时间用于America/Chicago
的时区。
ZoneId z = ZoneId.of( "America/Chicago" ) ;
ZonedDateTime zdt = ZonedDateTime.of( ldt , z ) ;
让我们生成标准ISO 8601格式的字符串,以检查当时在该区域中使用的偏移量。 ZonedDateTime::toString
方法明智地扩展了标准,以在方括号中附加区域的名称。
String output = zdt.toString() ;
输出:2020-01-23T15:00-06:00 [美国/芝加哥]
现在我们已经确定了ZonedDateTime
对象中的时刻。我们可以通过提取Instant
对象来适应UTC。
Instant instant = zdt.toInstant() ;
instant.toString():2020-01-23T21:00:00Z