Timezone conversion

后端 未结 12 1543
一向
一向 2020-11-22 11:25

I need to convert from one timezone to another timezone in my project.

I am able to convert from my current timezone to another but not from a different timezone to

12条回答
  •  执笔经年
    2020-11-22 11:55

    here a story: my user in US enters a date in a web page. My server gets this as a java.util.Date object. Date objects have no notion of time zone.

    so let's say user entered 11PM(== 4AM london time). For her this was 11PM US time. Your server gets this and interprets this as 11PM of JVM's timezone. but what you need is a Date object that represents 4AM.

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String timeStringInUS =  sdf.format("2020-05-04 23:00:00");
    
    SimpleDateFormat dateFormatInUS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    SimpleDateFormat dateFormatInUK = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    dateFormatInUS.setTimeZone(TimeZone.getTimeZone("America/New_York"));
    dateFormatInUK.setTimeZone(TimeZone.getTimeZone("Europe/London"));
    
    Date dateInUS = dateFormatInUS.parse(timeStringInUS);
    Date dateInUK = sdf.parse(dateFormatInUK.format(dateInUS));
    

提交回复
热议问题