[英]Day light saving issue
Using following : 使用以下内容:
public static void main(String[] args) throws ParseException {
System.out.println(convertDate("2017-03-12 02:00", true));
}
public static Date convertDate(final String dateStr, final Boolean isDateTime) throws ParseException{
Date tmpDate = null;
if ( dateStr == null || dateStr.isEmpty() ) {
return tmpDate;
}
String dateFormat = "yyyy-MM-dd";
// LOGGER.debug("Input date string: " + dateStr);
if (isDateTime) {
dateFormat = "yyyy-MM-dd HH:mm";
// TimeZone frTimeZone = TimeZone.getTimeZone("UTC");
// sdf.setTimeZone(frTimeZone);
}
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
try {
tmpDate = sdf.parse(dateStr);
} catch (ParseException e) {
}
return tmpDate;
}
output getting : Sun Mar 12 03:00:00 EDT 2017 expected output : Sun Mar 12 02:00:00 EDT 2017 输出结果:2017年3月12日星期日东部夏令时2017年预期输出:2017年3月12日星期日东部夏令时02:00
second try : 第二次尝试:
public static Date convertDate(final String dateStr, final Boolean isDateTime) throws ParseException{
Date tmpDate = null;
String dateFormat = "dd-M-yyyy hh:mm:ss a";
if (isDateTime) {
dateFormat = "yyyy-MM-dd HH:mm";
}
SimpleDateFormat sdfAmerica = new SimpleDateFormat(dateFormat);
Date date = sdfAmerica.parse(dateStr);
// TimeZone tz = TimeZone.getDefault();
DateTime dt = new DateTime(date);
DateTimeZone dtZone = DateTimeZone.forID("America/New_York");
DateTime dtus = dt.withZone(dtZone);
TimeZone tzInAmerica = dtZone.toTimeZone();
Date dateInAmerica = dtus.toLocalDateTime().toDate(); //Convert to LocalDateTime first
sdfAmerica.setTimeZone(tzInAmerica);
System.out.println("dateInAmerica"+dateInAmerica);
tmpDate=sdfAmerica.parse(dateStr);
boolean inDaylightTime=tzInAmerica.inDaylightTime(tmpDate);
if(inDaylightTime){
Calendar cal = Calendar.getInstance();
int hour=(tzInAmerica.getDSTSavings() / (1000 * 60 * 60));
System.out.println("hour::::"+hour);
cal.setTime(sdfAmerica.parse(dateStr));
System.out.println("date:::"+cal.getTime());
cal.add(Calendar.HOUR, hour);
tmpDate=cal.getTime();
}
return tmpDate;
}
output : Sun Mar 12 04:00:00 EDT 2017 输出:EDT 2017年3月12日04:00:00
However facing issue in getting correct output for date : 2017-03-12 02:00 但是在获取正确的日期输出时面临问题:2017-03-12 02:00
In your first example you say you expected Sun Mar 12 02:00:00 EDT 2017
but got Sun Mar 12 03:00:00 EDT 2017
. 在您的第一个示例中,您说您期望
Sun Mar 12 02:00:00 EDT 2017
但获得了Sun Mar 12 03:00:00 EDT 2017
。
Please note that Daylight Savings were turned on on Mar 12th. 请注意,夏令时已于3月12日启用。 So there should be no 2:00 AM EDT.
因此,美东时间不应该有凌晨2:00。 When the clock is about to reach 2:00 AM it becomes 3:00 AM.
当时钟即将达到2:00 AM时,它将变为3:00 AM。 So regardless of what your code is doing your expectation seems to be incorrect.
因此,无论您的代码在做什么,您的期望似乎都是错误的。
https://www.timeanddate.com/time/change/usa?year=2017 https://www.timeanddate.com/time/change/usa?year=2017
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.