日期API"/>
Java8 时间日期API
**
时间格式化LocalDate,DateTimeFormatter—>parse,ofParttern
**
**Instant:**瞬时实例。
**LocalDate:**本地日期,不包含具体时间 例如:2014-01-14 可以用来记录生日、纪念日、加盟日等。
**LocalTime:**本地时间,不包含日期。
**LocalDateTime:**组合了日期和时间,但不包含时差和时区信息。
**ZonedDateTime:**最完整的日期时间,包含时区和相对UTC或格林威治的时差。
新API还引入了ZoneOffSet和ZoneId类,使得解决时区问题更为简便。解析、格式化时间的DateTimeFormatter类也全部重新设计.
使用方法:
public static final DateTimeFormatter YYYYMMDD_PATTERN_FORMARTTER = DateTimeFormatter .ofPattern("yyyyMMdd");public static final DateTimeFormatter YYYY_MM_DD_PATTERN_FORMARTTER = DateTimeFormatter .ofPattern("yyyy_MM_dd");public static final DateTimeFormatter YYYYMMDDHHMMSS_PATTERN_FORMARTTER = DateTimeFormatter .ofPattern("yyyyMMddHHmmss");public static final DateTimeFormatter YYYY_MM_DD_HH_MM_SS_PATTERN_FORMARTTER = DateTimeFormatter .ofPattern("yyyy_MM_dd HH:mm:ss");//将“yyyy_MM_dd”格式字符串转换成“yyyyMMdd”格式字符串
private String getDateString(String str){LocalDate parse = **LocalDate**.parse(str, YYYY_MM_DD_PATTERN_FORMARTTER);String format = parse.format (YYYYMMDD_PATTERN_FORMARTTER );return format ;
}//将“yyyy_MM_dd HH:mm:ss”格式字符串转换成“yyyyMMddHHmmss”格式字符串
private String getDateString(String str){LocalDate parse = **LocalDateTime**.parse(str, YYYY_MM_DD_HH_MM_SS_PATTERN_FORMARTTER );String format = parse.format(YYYYMMDDHHMMSS_PATTERN_FORMARTTER );return format ;
}//将“yyyyMMdd”格式字符串转换成“yyyy_MM_dd”格式字符串
private String getDateString(String str){LocalDate parse = **LocalDate**.parse(str, YYYYMMDD_PATTERN_FORMARTTER );String format = parse.format (YYYY_MM_DD_PATTERN_FORMARTTER);return format ;
}//将“yyyyMMddHHmmss”格式字符串转换成“yyyy_MM_dd HH:mm:ss”格式字符串
private String getDateString(String str){LocalDate parse = **LocalDateTime**.parse(str, YYYYMMDDHHMMSS_PATTERN_FORMARTTER );String format = parse.format(YYYY_MM_DD_HH_MM_SS_PATTERN_FORMARTTER );return format ;
}
API使用:
public class TimeTest {public static void main(String[] args) {//获取当前时间LocalDate today = LocalDate.now();System.out.println("localDate:"+today);//output:localDate:2021-10-26//获取年、月、日信息int year = today.getYear();int month = today.getMonthValue();int day = today.getDayOfMonth();System.out.printf( "Year : %d Month : %d day : %d t %n" , year, month, day);//output: Year : 2021 Month : 10 day : 26 t //工厂方法LocalDate.of()创建任意日期LocalDate dateOfBirth = LocalDate.of( 2021 , 10 , 26);System.out.println( "create dateOfBirth is : " + dateOfBirth);//output: create dateOfBirth is : 2021-10-26//判断两个日期是否相等,如果比较的日期是字符型的,需要先解析成日期对象再作判断LocalDate date1 = LocalDate.of( 2021, 10 , 26 );if (date1.equals(today)){System.out.printf( "Today %s and date1 %s are same date %n" , today, date1);}//output:Today 2021-10-26 and date1 2021-10-26 are same date//通过 MonthDay来检查周期性事件MonthDay birthday = MonthDay.of(dateOfBirth.getMonth(), dateOfBirth.getDayOfMonth());MonthDay currentMonthDay = MonthDay.from(today);if (currentMonthDay.equals(birthday)){System.out.println( "happy birthday !!!" );} else {System.out.println( "Sorry, today is not your birthday" );}//output:happy birthday !!!//获取时间使用的是LocalTime类,默认的格式是hh:mm:ss:nnnLocalTime time = LocalTime.now();System.out.println( "local time now : " + time);//output:local time now : 17:10:52.862//在现有的时间上增加2小时LocalTime newTime = time.plusHours( 2 );System.out.println( "Time after 2 hours : " + newTime);//output:Time after 2 hours : 19:10:52.862//计算一周后的日期LocalDate nextWeek = today.plus( 1 , ChronoUnit.WEEKS);System.out.println( "Today is : " + today);//output:Today is : 2021-10-26System.out.println( "Date after 1 week : " + nextWeek);//output:Date after 1 week : 2021-11-02//计算一年前或一年后的日期LocalDate previousYear = today.minus( 1 , ChronoUnit.YEARS);System.out.println( "Date before 1 year : " + previousYear);//output:Date before 1 year : 2020-10-26LocalDate nextYear = today.plus( 1 , ChronoUnit.YEARS);System.out.println( "Date after 1 year : " + nextYear);//output:Date after 1 year : 2022-10-26//Clock时钟类用于获取当时的时间戳,或当前时区下的日期时间信息.// 以前用到System.currentTimeInMillis()和TimeZone.getDefault()的地方都可用Clock替换。Clock clock = Clock.systemUTC();System.out.println( "Clock : " + clock);//output:Clock : SystemClock[Z]Clock defaultClock = Clock.systemDefaultZone();System.out.println( "defaultClock : " + defaultClock);//output:defaultClock : SystemClock[Asia/Shanghai]//判断日期是早于还是晚于另一个日期LocalDate tomorrow = LocalDate.of( 2022 , 1 , 15 );if (tomorrow.isAfter(today)){System.out.println( "Tomorrow comes after today" );}LocalDate yesterday = today.minus( 1 , DAYS);if (yesterday.isBefore(today)){System.out.println( "Yesterday is day before today" );}//output:Tomorrow comes after today//output:Yesterday is day before today//ZoneId来处理特定时区,ZoneDateTime类来表示某时区下的时间ZoneId america = ZoneId.of( "America/New_York" );LocalDateTime localtDateAndTime = LocalDateTime.now();ZonedDateTime dateAndTimeInNewYork = ZonedDateTime.of(localtDateAndTime, america );System.out.println( "Current date and time in a particular timezone : " + dateAndTimeInNewYork);//output:Current date and time in a particular timezone : 2021-10-26T17:10:52.866-04:00[America/New_York]//YearMonth:用于表示信用卡到期日、FD到期日、期货期权到期日等。// 还可以用这个类得到 当月共有多少天,YearMonth实例的lengthOfMonth()方法可以返回当月的天数YearMonth currentYearMonth = YearMonth.now();System.out.printf( "Days in month year %s: %d%n" , currentYearMonth, currentYearMonth.lengthOfMonth());//output:Days in month year 2021-10: 31YearMonth creditCardExpiry = YearMonth.of( 2018 , Month.FEBRUARY);System.out.printf( "Your credit card expires on %s %n" , creditCardExpiry);//output:Your credit card expires on 2018-02 //检查闰年if (today.isLeapYear()){System.out.println( "This year is Leap year" );} else {System.out.println( "2014 is not a Leap year" );}//output:2014 is not a Leap year//计算两个日期之间的天数和月数:计算当天和将来某一天之间的月数LocalDate future = LocalDate.of( 2022 , Month.MARCH, 14 );Period periodToNextJavaRelease = Period.between(today, future);System.out.println( "Months left between today and future : "+ periodToNextJavaRelease.getMonths() );//output:Months left between today and future : 4//ZoneOffset类用来表示时区,举例来说印度与GMT或UTC标准时区相差+05:30,// 可以通过ZoneOffset.of()静态方法来获取对应的时区。// 一旦得到了时差就可以通过传入LocalDateTime和ZoneOffset来创建一个OffSetDateTime对象LocalDateTime datetime = LocalDateTime.of( 2014 , Month.JANUARY, 14 , 19 , 30 );ZoneOffset offset = ZoneOffset.of( "+05:30" );OffsetDateTime date = OffsetDateTime.of(datetime, offset);System.out.println( "Date and Time with timezone offset in Java : " + date);//output:Date and Time with timezone offset in Java : 2014-01-14T19:30+05:30//获取当前的时间戳,等同于 Java 8之前的Date类Instant timestamp = Instant.now();System.out.println( "What is value of this instant " + timestamp);//output:What is value of this instant 2021-10-26T09:10:52.873Z//将Instant转换成java.util.DateDate date2 = Date.from(timestamp);System.out.println( "date2 :" + timestamp);//output:date2: 2021-10-26T09:10:52.873Z//将Date类转换成Instant类Instant instant = date2.toInstant();System.out.println( "instant: " + timestamp);//output:instant :2021-10-26T09:10:52.873Z//使用预定义的格式化工具去解析或格式化日期:"20140116"-->"2014-01-16"String dayAfterTommorrow = "20140116" ;LocalDate formatted = LocalDate.parse(dayAfterTommorrow,DateTimeFormatter.BASIC_ISO_DATE);System.out.printf( "Date generated from String %s is %s %n" ,dayAfterTommorrow, formatted);//output:Date generated from String 20140116 is 2014-01-16 //使用自定义格式化工具解析日期String goodFriday = "Apr 18 2014" ;try {DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "MMM dd yyyy" );LocalDate holiday = LocalDate.parse(goodFriday, formatter);System.out.printf( "Successfully parsed String %s, date is %s%n" , goodFriday, holiday);} catch (DateTimeParseException ex) {System.out.printf( "%s is not parsable!%n" , goodFriday);ex.printStackTrace();}//Output :Successfully parsed String Apr 18 2014, date is 2014-04-18//把日期转换成字符串LocalDateTime arrivalDate = LocalDateTime.now();try {DateTimeFormatter format = DateTimeFormatter.ofPattern( "MMM dd yyyy hh:mm a" );String landing = arrivalDate.format(format);System.out.printf( "Arriving at : %s %n" , landing);} catch (DateTimeException ex) {System.out.printf( "%s can't be formatted!%n" , arrivalDate);ex.printStackTrace();}//Output : Arriving at : Jan 14 2014 04:33 PM}//还可以针对clock时钟做比较,像下面这个例子://这种方式在不同时区下处理日期时会非常管用public class MyClass {private Clock clock; // dependency injectpublic void process(LocalDate eventDate) {if (eventDate.isBefore(LocalDate.now(clock))){System.out.println(".....");}}}
}
总结:
1)提供了javax.time.ZoneId 获取时区。
2)提供了LocalDate和LocalTime类。
3)Java 8 的所有日期和时间API都是不可变类并且线程安全,而现有的Date和Calendar API中的java.util.Date和SimpleDateFormat是非线程安全的。
4)主包是 java.time,包含了表示日期、时间、时间间隔的一些类。里面有两个子包java.time.format用于格式化, java.time.temporal用于更底层的操作。
5)时区代表了地球上某个区域内普遍使用的标准时间。每个时区都有一个代号,格式通常由区域/城市构成(Asia/Tokyo),在加上与格林威治或 UTC的时差。例如:东京的时差是+09:00。
6)OffsetDateTime类实际上组合了LocalDateTime类和ZoneOffset类。用来表示包含和格林威治或UTC时差的完整日期(年、月、日)和时间(时、分、秒、纳秒)信息。
7)DateTimeFormatter 类用来格式化和解析时间。与SimpleDateFormat不同,这个类不可变并且线程安全,需要时可以给静态常量赋值。 DateTimeFormatter类提供了大量的内置格式化工具,同时也允许你自定义。在转换方面也提供了parse()将字符串解析成日期,如果解析出错会抛出DateTimeParseException。DateTimeFormatter类同时还有format()用来格式化日期,如果出错会抛出DateTimeException异常。
8)再补充一点,日期格式“MMM d yyyy”和“MMM dd yyyy”有一些微妙的不同,第一个格式可以解析“Jan 2 2014”和“Jan 14 2014”,而第二个在解析“Jan 2 2014”就会抛异常,因为第二个格式里要求日必须是两位的。如果想修正,你必须在日期只有个位数时在前面补零,就是说“Jan 2 2014”应该写成 “Jan 02 2014”。
参考:
更多推荐
Java8 时间日期API
发布评论