Date Conversion In java Web Application

爱⌒轻易说出口 提交于 2019-12-20 04:10:23

问题


    String date1 = "13/03/2014 16:56:46 AEDT";

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss z");
    sdf.setTimeZone(TimeZone.getTimeZone("GMT+12"));
    java.util.Date convertedDate = (java.util.Date) sdf.parse(date1);
    SimpleDateFormat outFormatter = new SimpleDateFormat("EE MMM dd yyyy HH:mm:ss z");
    outFormatter.setTimeZone(TimeZone.getTimeZone("GMT+12"));
    String output = outFormatter.format(convertedDate);
    System.out.println("Date in NZ Timezone : " + output);

I am trying to convert AEDT date into dd/MM/yyyy HH:mm:ss z but it gives me exception :

Exception in thread "main" java.text.ParseException: Unparseable date: "13/03/2014 16:56:46 AEDT" at java.text.DateFormat.parse(DateFormat.java:337)

Please help me with this....

I need to convert users time in to my UTC time for making it same through my web-application ...


回答1:


It means that Java does not support AEDT abbreviation, but since you know timezone offset you can doit this way

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT+12"));
java.util.Date convertedDate = (java.util.Date) sdf.parse(date1);



回答2:


Your code seems to be right, but AEDT is not a valid General Time Zone. Thats the reason for the java.text.ParseException. Instead you can do:

String date1 = "13/03/2014 16:56:46 "+TimeZone.getTimeZone("GMT-11").getID();

Input:

13/03/2014 16:56:46 GMT+12:00

Output:

Date in NZ Timezone : Fr Mrz 14 2014 15:56:46 GMT+12:00

It seems to work right:)

From the Doc's:

Three-letter time zone IDs

For compatibility with JDK 1.1.x, some other three-letter time zone IDs (such as "PST", "CTT", "AST") are also supported. However, their use is deprecated because the same abbreviation is often used for multiple time zones (for example, "CST" could be U.S. "Central Standard Time" and "China Standard Time"), and the Java platform can then only recognize one of them.



来源:https://stackoverflow.com/questions/22371612/date-conversion-in-java-web-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!