尝试从美国/东部时区转换日期时出现java解析异常

wn9m85ua  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(302)

下面是解析date的代码,它抛出了parse exception。有人能帮忙解决这个问题吗?我不想使用任何其他第三方api。

DateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ssZ");
    Date newDate;
    try {
        newDate = df.parse("28-04-2016 23:59:59 US/Eastern");
            df.setTimeZone(TimeZone.getTimeZone("UTC"));
            String strdate = df.format(newDate);
            System.out.println("The date and time in :: UTC is ::" + strdate);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
bvk5enib

bvk5enib1#

简单JavaAPI中的时区处理并不是那么简单,这就是为什么java在Java8中包含了joda时间。为了解决你的问题,你可以采取如下措施:

String sourceDateTimeTz = "28-04-2016 23:59:59 US/Eastern";
    String sourceDateTime = sourceDateTimeTz.substring(0, 19);
    TimeZone sourceTz = TimeZone.getTimeZone(sourceDateTimeTz.substring(20));

    DateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");

    Date sourceDate;
    try {
        sourceDate = df.parse(sourceDateTime);
        Calendar sourceCalendar = Calendar.getInstance();
        sourceCalendar.setTime(sourceDate);
        sourceCalendar.setTimeZone(sourceTz);

        Calendar targetCalendar = Calendar.getInstance();
        for (int field : new int[] { Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH, Calendar.HOUR,
                Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND }) {
            targetCalendar.set(field, sourceCalendar.get(field));
        }
        targetCalendar.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date targetDate = targetCalendar.getTime();

        System.out.println(df.format(targetDate));

    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

相关问题