Parsing Java String into GMT Date
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"));
}
}
You are using format.setTimeZone(TimeZone.getTimeZone("GMT"));
in the formatter, which is being used in formatting the string into date ie
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);
System.out.println(format.parse("2012-10-29T12:57:00-0000"));
Parses the date as GMT and returns a Date object. Then it prints it out (using the default toString()-method). This just uses the settings of your computer. so you should use:
Date parsedDate=format.parse("2012-10-29T12:57:00-0000");
System.out.println(format.format(parsedDate));
Complete working example
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class Main
{
public static void main(String[] args)
{
final SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss z", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(sdf.format(new Date()));
// ^^^ note printing the results of sdf.format()
// not a raw `Date`
}
}
result : 31-10-2012 08:32:01 UTC
Note what I am actually printing out!
下一篇: 将Java字符串解析为GMT日期