使用以下命令:
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;
}输出获取: Sun Mar 12 03:00:00 EDT 2017预期输出: Sun Mar 12 02:00:00 EDT 2017
第二次尝试:
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;
}输出: Sun Mar 12 04:00:00 EDT 2017
但是,在获取日期: 2017-03-12 02:00的正确输出时遇到问题
发布于 2017-03-28 18:39:10
在第一个示例中,您说期望的是Sun Mar 12 02:00:00 EDT 2017,但得到的是Sun Mar 12 03:00:00 EDT 2017。
请注意,夏令时是在3月12日启用的。所以不应该有美国东部夏令时2:00。当时钟快到凌晨2点时,就变成了凌晨3点。因此,不管你的代码在做什么,你的期望似乎是不正确的。
https://stackoverflow.com/questions/43066108
复制相似问题