How to set time zone of a java.util.Date?
I have parsed a java.util.Date
from a String
but it is setting the local time zone as the time zone of the date
object.
The time zone is not specified in the String
from which Date
is parsed. I want to set a specific time zone of the date
object.
How can I do that?
Use DateFormat. For example,
SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
isoFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = isoFormat.parse("2010-05-23T09:01:02");
Be aware that java.util.Date
objects do not contain any timezone information by themselves - you cannot set the timezone on a Date
object. The only thing that a Date
object contains is a number of milliseconds since the "epoch" - 1 January 1970, 00:00:00 UTC.
As ZZ Coder shows, you set the timezone on the DateFormat
object, to tell it in which timezone you want to display the date and time.
You could also set the timezone at the JVM level
Date date1 = new Date();
System.out.println(date1);
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
// or pass in a command line arg: -Duser.timezone="UTC"
Date date2 = new Date();
System.out.println(date2);
output:
Thu Sep 05 10:11:12 EDT 2013
Thu Sep 05 14:11:12 UTC 2013
链接地址: http://www.djcxy.com/p/18668.html