I'm trying to parse a String that represents a date using GMT, but it prints out in my timezone on my PC (pacific). When I run the below I get the below output. Any ideas on how to get the parse to parse and return a GMT date? If you look below I'm setting the timezone using format.setTimeZone(TimeZone.getTimeZone("GMT")); but its not producing the desired result.
output from below code:
Mon Oct 29 05:57:00 PDT 2012
package javaapplication1;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
public class JavaApplication1 {
public static void main(String[] args) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
format.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(format.parse("2012-10-29T12:57:00-0000"));
}
}
We can convert String to Date in java using parse() method of DateFormat and SimpleDateFormat classes. To learn this concept well, you should visit DateFormat and SimpleDateFormat classes.
Using the Parse API With a Custom Formatter. Converting a String with a custom date format into a Date object is a widespread operation in Java. For this purpose we'll use the DateTimeFormatter class, which provides numerous predefined formatters, and allows us to define a formatter.
To parse your "Thu Jun 18 20:56:02 EDT 2009" date string you need a SimpleDateFormat like this (roughly): SimpleDateFormat parser=new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy"); Use this to parse the string into a Date, and then your other SimpleDateFormat to turn that Date into the format you want.
You are using format.setTimeZone(TimeZone.getTimeZone("GMT"));
in the formatter, which is being used in formatting the string into date i.e.
Date date = format.parse("2012-10-29T12:57:00-0000");
is parsed treating 2012-10-29T12:57:00-0000
was a GMT
value, but you are printing date
which uses local timezome in printing hence you are noticing the difference.
If you want to print the date back in GMT
, please use:
String formattedDate = format.format(date);
and print the formattedDate
. This will be GMT
.
System.out.println(formattedDate);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With