时间和时区
SimpleDateFormat 可以用来验证和转换带时区的时间数据,无论是Date或者是String。
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))); } }
运行结果:
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