我从一个字符串中解析了一个java.util.Date,但它将本地时区设置为date对象的时区。
在解析Date的字符串中没有指定时区。我想设置date对象的特定时区。
我该怎么做呢?
我从一个字符串中解析了一个java.util.Date,但它将本地时区设置为date对象的时区。
在解析Date的字符串中没有指定时区。我想设置date对象的特定时区。
我该怎么做呢?
当前回答
calendar是使用JDK类处理时区的常用方法。Apache Commons还有一些可能有用的替代方案/实用程序。Edit Spong的留言提醒我,我听说Joda-Time真的很不错(尽管我自己没有用过)。
其他回答
如果你必须只使用标准JDK类,你可以使用这个:
/**
* Converts the given <code>date</code> from the <code>fromTimeZone</code> to the
* <code>toTimeZone</code>. Since java.util.Date has does not really store time zome
* information, this actually converts the date to the date that it would be in the
* other time zone.
* @param date
* @param fromTimeZone
* @param toTimeZone
* @return
*/
public static Date convertTimeZone(Date date, TimeZone fromTimeZone, TimeZone toTimeZone)
{
long fromTimeZoneOffset = getTimeZoneUTCAndDSTOffset(date, fromTimeZone);
long toTimeZoneOffset = getTimeZoneUTCAndDSTOffset(date, toTimeZone);
return new Date(date.getTime() + (toTimeZoneOffset - fromTimeZoneOffset));
}
/**
* Calculates the offset of the <code>timeZone</code> from UTC, factoring in any
* additional offset due to the time zone being in daylight savings time as of
* the given <code>date</code>.
* @param date
* @param timeZone
* @return
*/
private static long getTimeZoneUTCAndDSTOffset(Date date, TimeZone timeZone)
{
long timeZoneDSTOffset = 0;
if(timeZone.inDaylightTime(date))
{
timeZoneDSTOffset = timeZone.getDSTSavings();
}
return timeZone.getRawOffset() + timeZoneDSTOffset;
}
功劳归于这篇文章。
请注意,java.util.Date对象本身不包含任何时区信息—您不能在Date对象上设置时区。Date对象所包含的唯一内容是从“epoch”开始的毫秒数——1970年1月1日00:00:00 UTC。
如ZZ Coder所示,您可以在DateFormat对象上设置时区,以告诉它您希望在哪个时区显示日期和时间。
您还可以在JVM级别设置时区
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);
输出:
Thu Sep 05 10:11:12 EDT 2013
Thu Sep 05 14:11:12 UTC 2013
package org.example;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class time {
public static void main(String[] args) {
SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd HH:mm");
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Jakarta"));
Date date=new Date();
sdf.format(date);
System.out.println(sdf.format(date));
}
}
DateFormat使用。例如,
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");