時(shí)間加減
Date currentDate = new Date(System.currentTimeMillis()); Calendar cal = Calendar.getInstance(); cal.setTime(currentDate); cal.add(Calendar.DAY_OF_MONTH, -1);//減一天時(shí)間 startTime=outputFormat.format(cal.getTime());
開發(fā)跨地域的程序時(shí),常需要進(jìn)行時(shí)區(qū)轉(zhuǎn)換,一個(gè)設(shè)計(jì)優(yōu)良的系統(tǒng),也必須考慮對(duì)多時(shí)區(qū)的支持。JDK提供了很多方便的機(jī)制和工具,來幫助我們解決時(shí)區(qū)轉(zhuǎn)換問題。
解決跨時(shí)區(qū)問題的關(guān)鍵在于時(shí)間的記錄形式。若將時(shí)間單純的記錄成“2011-05-14 23:30:00”,其中蘊(yùn)含的信息并不足以進(jìn)行時(shí)區(qū)轉(zhuǎn)換,因?yàn)闊o法獲知這是中國的23點(diǎn)30,還是美國的23點(diǎn)30,更不用說復(fù)雜的夏令時(shí)問題了。
我們可以使用一個(gè)long類型的變量來記錄時(shí)間,該變量的值等于從1970年1月1日 00:00:00 GMT到記錄時(shí)間點(diǎn)以來的毫秒數(shù),其中GMT代表格林威治標(biāo)準(zhǔn)時(shí)間,通過這個(gè)差值,可以獲得記錄時(shí)間點(diǎn)的格林威治(零時(shí)區(qū))時(shí)間,進(jìn)而能方便的轉(zhuǎn)換成全世界各時(shí)區(qū)的時(shí)間。(很多數(shù)據(jù)庫引擎就是如此處理時(shí)間類型數(shù)據(jù))
在Java中,有兩個(gè)常用方法來獲取以上描述的值:
此外,我們還需要借助java.util.TimeZone類,來獲取特定的時(shí)區(qū),JRE安裝目錄下的\lib\zi文件夾列出了所有TimeZoneID,如:Asia/Shanghai。最后,使用java.text.SimpleDateFormat類提供的方法進(jìn)行轉(zhuǎn)換,并格式化輸出。
//1. 將系統(tǒng)當(dāng)前時(shí)間轉(zhuǎn)換成美國東部時(shí)間 // America/Los_Angeles 洛杉磯時(shí)間TimeZone timeZoneNY = TimeZone.getTimeZone("America/New_York");SimpleDateFormat outputFormat = new SimpleDateFormat("EEE MMM d HH:mm:ss Z yyyy", Locale.US);outputFormat.setTimeZone(timeZoneNY);Date date = new Date(System.currentTimeMillis());System.out.println(outputFormat.format(date));
//2. 將一個(gè)以字符串形式輸入的北京時(shí)間轉(zhuǎn)換成美國東部時(shí)間String inputDate = "2011-05-14 23:30:00";TimeZone timeZoneSH = TimeZone.getTimeZone("Asia/Shanghai");TimeZone timeZoneNY = TimeZone.getTimeZone("America/New_York");SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");inputFormat.setTimeZone(timeZoneSH);Date date = null;try { date = inputFormat.parse(inputDate);} catch (ParseException e) {} SimpleDateFormat outputFormat = new SimpleDateFormat("EEE MMM d HH:mm:ss Z yyyy", Locale.US);outputFormat.setTimeZone(timeZoneSH);System.out.println("Asia/Shanghai:" + outputFormat.format(date));outputFormat.setTimeZone(timeZoneNY);System.out.println("America/New_York:" + outputFormat.format(date));
那么,夏令時(shí)(DST)的問題怎么解決呢?令人高興的是,JDK(or JRE)已自動(dòng)為我們進(jìn)行了夏令時(shí)處理。可以做個(gè)試驗(yàn),來驗(yàn)證以上第2段代碼能適用于夏令時(shí)轉(zhuǎn)換。美國在2011年開始和結(jié)束夏令時(shí)的時(shí)間是:3.13 2AM和11.6 2AM。
聯(lián)系客服