Java 解析日期重置时区
我正在尝试根据机场设置Date对象上的时区。 当我再次将其从字符串解析为日期时,它将时区从EST重置为本地时区CSTJava 解析日期重置时区,java,date,Java,Date,我正在尝试根据机场设置Date对象上的时区。 当我再次将其从字符串解析为日期时,它将时区从EST重置为本地时区CST private Date formatDate(final Date date, final FlightStop stop) { DateFormat sdf = new SimpleDateFormat("MM/dd/yy hh:mm aa zzz"); sdf.setTimeZone(TimeZone.getTimeZone(stop.getAirport
private Date formatDate(final Date date, final FlightStop stop) {
DateFormat sdf = new SimpleDateFormat("MM/dd/yy hh:mm aa zzz");
sdf.setTimeZone(TimeZone.getTimeZone(stop.getAirport().getTimeZone().getID()));
try {
LOG.debug("before parsing -> sdf.format(date) : " + sdf.format(date)); //03/03/20 10:45 AM EST
LOG.debug("after parsing -> sdf.parse(sdf.format(date)) : " + sdf.parse(sdf.format(date))); //after parsing Tue Mar 03 09:45:00 CST
return sdf.parse(sdf.format(date));
} catch (Exception e) {
return new Date();
}
}
更新:
方法调用:
public void sendMessage(final Date endingStopDate, final FlightStop endingStop) {
Date endDate = formatDate(endingStopDate, endingStop);
traveler.setDate(endDate);
日期
是UTC
不能为java.util.Date
设置时区。该类表示UTC中的一个时刻
java.time
您正在使用可怕的日期时间类,这些类在几年前被现代java.time类所取代
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
要生成标准格式的字符串,请调用toString
ZonedDateTime::toString
通过在方括号中添加时区名称,明智地扩展了标准
要生成其他格式的字符串,请使用DateTimeFormatter
。搜索堆栈溢出以了解更多信息。这已经被报道了数百次了
DateTimeFormatter f = DateTimeFormatter.ofPattern( … ) ;
String output = zdt.format( f );
和解析
ZonedDateTime zdt = ZonedDateTime.parse( input , f ) ;
不要以自定义格式交换数据值。因此,不要来回生成和解析自定义字符串。仅使用标准格式以文本方式交换日期时间值。这样做时,通常最好调整到UTC
zdt.toInstant().toString()
在调用该方法的地方张贴代码。
Date
&公司是一个丑陋的烂摊子,在单个类中包含不直观的API和不相关的信息。是否可以选择使用java.time
包?它可能很复杂,但它与时间和日期一样复杂,仅此而已……我建议您不要使用Date
和SimpleDateFormat
。这些类设计得很糟糕,而且早已过时,后者尤其是出了名的麻烦。而是使用ZoneDateTime
和ZoneId
,这两种方法都来自。也不要依赖三个字母的时区缩写,它们通常是模棱两可的,通常不是真正的时区。