简体   繁体   中英

How to convert date strings from different TimeZones to Date object in one TimeZone

Im working on an RSS reader software. I get items with their pubDate (publish date) values as string, convert them to Date object, and put them to my DB. However, when I check my DB, I saw some interesting values such as the date of tomorrow.

I research this situation and found that it is about time zone value Z. For example when I get "Mon, 26 May 2014 21:24:29 -0500", it becomes "2014-05-27 05:24:29", the next day !

All I want is to get dates in any timezone and convert them to date in common timezone, such as my country's.

Here is my code :

 public static String convert(String datestr) throws ParseException {
    DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
    Date date = formatter.parse(datestr);

    SimpleDateFormat resultFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    return  resultFormatter.format(date);
}

And I use the method like that :

 System.out.println(convert("Mon, 26 May 2014 21:24:29 -0500"));

The output is : 2014-05-27 05:24:29

Any idea ?

Since you haven't set a time zone, it's using your system's default.

Set a specific IANA time zone .

SimpleDateFormat resultFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
resultFormatter.setTimeZone(TimeZone.getTimeZone("America/New_York"));
return resultFormatter.format(date);

This is working as expected. The date is converted as per your system's timezone.

Check the UTC offset of your system and replace it in the sample date string and look at the output.


For eg: India is UTC+5:30

String datestr="Mon, 26 May 2014 21:24:29 +0530";

output:

2014-05-26 21:24:29

Alternate solution

If you don't want to consider the timezone of the input date string then simply truncate this information and remove zzz from pattern as well as shown in below code:

String datestr = "Mon, 26 May 2014 21:24:29 -0530";
datestr = datestr.replaceAll("\\s[-+](\\d+)$", ""); // truncate the timezone info if not needed

DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss"); // remove zzz from the pattern
Date date = formatter.parse(datestr);

SimpleDateFormat resultFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(resultFormatter.format(date));

Looks like you passed a Date with timezone, but given a wrong format. If you are passing timezone like "-0500" you should rather use:

DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");

Remember that the system will always display the date using the current, default timezone (TimeZone.getDefault()) unless you override it by:

resultFormatter.setTimeZone(...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM