How to set time zone of a java.util.Date?

后端 未结 10 1806
我寻月下人不归
我寻月下人不归 2020-11-22 01:45

I have parsed a java.util.Date from a String but it is setting the local time zone as the time zone of the date object.

The ti

10条回答
  •  孤街浪徒
    2020-11-22 01:56

    This code was helpful in an app I'm working on:

        Instant date = null;
        Date sdf = null;
        String formatTemplate = "EEE MMM dd yyyy HH:mm:ss";
        try {
            SimpleDateFormat isoFormat = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss");
            isoFormat.setTimeZone(TimeZone.getTimeZone(ZoneId.of("US/Pacific")));
            sdf = isoFormat.parse(timeAtWhichToMakeAvailable);
            date = sdf.toInstant();
    
        } catch (Exception e) {
            System.out.println("did not parse: " + timeAtWhichToMakeAvailable);
        }
    
        LOGGER.info("timeAtWhichToMakeAvailable: " + timeAtWhichToMakeAvailable);
        LOGGER.info("sdf: " + sdf);
        LOGGER.info("parsed to: " + date);
    

提交回复
热议问题