IST to EST Time Conversion In Java

后端 未结 3 968
醉话见心
醉话见心 2021-01-27 09:20

I have a Date field in Java in IST Time. I want to convert the same to EST Time and the output should be as a Date Type only. I am able to accomplish the same using the below pi

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-27 10:16

    Should you add z for time-zone pattern in your SimpleDateFormat pattern?

    So, it should be DateFormat timeFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z"). I changed your code like this:

    public static void main(String[] args) throws ParseException {
        SimpleDateFormat dateTimeFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z");
        dateTimeFormat.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
        Date date = new Date();
    
        System.out.println(dateTimeFormat.format(date)); // this print IST Timezone
    
        DateFormat timeFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z");
        timeFormat.setTimeZone(TimeZone.getTimeZone("America/New_York"));
    
        String estTime = timeFormat.format(date);
        date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z", Locale.ENGLISH).parse(estTime);
    
        System.out.println(timeFormat.format(date)); // this print EDT Timezone currently (on March)
    }
    

    In last print statement, current date format is printed with EDT Timezone (Eastern Daylight Time). Maybe because of this.

提交回复
热议问题