Date with timezone convert

4023 ワード

中国は行政の上で全国各地に対してすべて1つの統一的な時区を定義して、つまり私達の通常言う“北京時間”です.アメリカ大陸本土には5つの主要タイムゾーン(Arizona州単独タイムゾーン)があり、ハワイタイムゾーンとアラスカタイムゾーンを加えている.国土面積の小さいオーストラリアには5つのタイムゾーンがある.しかし、私たちが開発したアプリケーションが複数のタイムゾーンの共有使用をサポートすることを考慮する場合は、Javaのタイムゾーンを理解する必要があります.たとえば、あるタイムゾーンで定義された時間を別のタイムゾーンに変換して表示する方法などの問題があります.
グローバルタイムゾーンリファレンス[url]http://greenwichmeantime.com/time-zone/[/url]
最近のお客様は、取得日について、申請者が存在するタイムゾーンに基づいて計算する必要があります.
例えば、アメリカ西部のCA州から来た人は、アメリカ東部のIL州にいて、Serverはどこにいてもいます.
CurrentDate(現在時刻)は、サーバ時間に準じて申請者が州から来た時刻に換算されるべきです.
現在の時間は1日違うかもしれないからです.

// , new Date() Server
new Date();

JavaのDate型はtimezoneにサポートされていませんが、現在はコード日付がDateで、DBもDate型を保存しています.
calendarInstance.getTime()を使用してDateに変換することはよく知られています

// PST( ) 。
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("PST"));
// 。
Calendar calendar2 = Calendar.getInstance();

System.out.println(calendar.getTime() + " " + calendar.getTimeInMillis());
System.out.println(calendar2.getTime() + " " + calendar2.getTimeInMillis());

驚いたことに、直接このように変換して、打った結果は同じだった.
その後、自分のコードを書くと、みんながコードを書くときにもタイプの問題に遭遇したことがあると信じています.もっと良い方法があれば、教えてください.


private static Map US_TimeZoneMap = null;

/**
* Get right timezone date by calendar
*
* @param stateCode state name
* @return Date timezoneDate
*/
@SuppressWarnings("deprecation")
public static Date getTimezoneDate(String stateCode)
{
Calendar calendar = Calendar.getInstance(getTimezone(stateCode));
Date date = new Date(calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH));
return date;
}

/**
* Get timezone type by state name
*
* @param stateCode
* @return TimeZone
*/
public static TimeZone getTimezone(String stateCode)
{
return TimeZone.getTimeZone(initializeTimezoneMap().get(stateCode));
}

/**
* Initialize a map store timezone info
*
* @return Map timezone Map
*/
public static Map initializeTimezoneMap()
{
if (US_TimeZoneMap == null)
{
US_TimeZoneMap = new HashMap();
US_TimeZoneMap.put("CA", "PST");
US_TimeZoneMap.put("CO", "MST");
// ...
US_TimeZoneMap.put("IL", "CST");
US_TimeZoneMap.put("GA", "EST");
}

return US_TimeZoneMap;
}

この記事ではjava timezoneを紹介していますが、詳しい[url]http://www.ibm.com/developerworks/cn/java/l-datetime/part2/index.html[/url]
Java date and time classes---[b]Joda[/b].[url]http://joda-time.sourceforge.net/index.html[/url]
[quote]Joda-Time has been created to radically change date and time handling in Java. The JDK classes Date and Calendar are very badly designed, have had numerous bugs and have odd performance effects. ...[/quote]

// get current moment in default time zone
DateTime dt = new DateTime();
// translate to London local time
DateTime dt2 = dt.withZone(DateTimeZone.forID("America/Los_Angeles"));

// This is similar in concept to the default time zone of the java.util.TimeZone class.
DateTimeZone defaultZone = DateTimeZone.getDefault();
DateTimeZone.setDefault(myZone);

試してみると、いい感じで、TIMEZONEを応援するのはいいですね.後で考えてもいいです.
SUNのDateの代わりにjodaのDatetimeを直接使う海外プロジェクトもあります