SimpleDateFormat 能夠用來驗證和轉換帶時區的時間數據,不管是Date或者是String。java
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class test { public static void main(String[] args) throws ParseException { SimpleDateFormat dfNoTimezone = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss"); SimpleDateFormat dfTimezone = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); Date now = new Date(); // 將本地時間轉換成帶時區格式的時間 System.out.println("local time : " + dfNoTimezone.format(now)); System.out.println("timezone time : " + dfTimezone.format(now)); // 將帶時區格式的時間轉成本地時間 String chTime = "2018-01-08T09:30:32+0800"; String utcTime = "2018-01-08T09:30:32+0000"; String usTime = "2018-01-08T09:30:32-0700"; System.out.println("East 8: " + dfNoTimezone.format(dfTimezone.parse(chTime))); System.out.println("UTC : " + dfNoTimezone.format(dfTimezone.parse(utcTime))); System.out.println("West 7: " + dfNoTimezone.format(dfTimezone.parse(usTime))); } }
運行結果:spa
local time : 2018-01-07T17:00:35 timezone time : 2018-01-07T17:00:35+0800 East 8: 2018-01-08T09:30:32 UTC : 2018-01-08T17:30:32 West 7: 2018-01-09T00:30:32