本来想写下Java 8的日期/时间API,发现已经有篇不错的文章了,那就直接转载吧~
PS:主要内容没变,做了部分修改。
转载: 风一样的码农 http://www.cnblogs.com/chenpi/
原文链接: journaldev 翻译: ImportNew.com - Justin Wu
译文链接: http://www.importnew.com/14140.html
侵删!!!
Java 8中的日期/时间(Date/Time)API是开发人员最受追捧的变化之一,Java从一开始就没有对日期/时间一致性处理的方法,因此在Java 8中新增的日期/时间API也是除Java核心API以外另一项倍受欢迎的内容。
在开始研究Java 8日期/时间API之前,让我们先来看一下为什么我们需要这样一个新的API。在Java 8之前中,日期和时间相关的类存在如下问题:
在现有的日期和日历类中定义的方法还存在一些其他的问题,但以上问题已经很清晰地表明:Java需要一个健壮的日期/时间类。这也是为什么Joda Time库,作为旧的日期/时间API的替换者,在Java 8日期/时间需求中扮演重要角色的原因。
Java 8日期/时间API是JSR-310规范的实现,它的目标是克服旧的日期/时间API实现中所有的缺陷,新的日期/时间API的一些设计原则如下:
Java日期/时间API由以下包组成:
我们已经浏览了Java 8日期/时间API中的大多数重要部分,是时候根据示例深入了解其中的核心类了。
LocalDate是一个不可变的类,它表示默认格式(yyyy-MM-dd)的日期,我们可以使用now()方法得到当前时间,也可以提供输入年份、月份和日期的输入参数来创建一个LocalDate实例。该类为now()方法提供了重载方法,我们可以传入ZoneId来获得指定时区的日期。该类提供与java.sql.Date相同的功能,对于如何使用该类,我们来看一个简单的例子。
1 import java.time.LocalDate; 2 import java.time.Month; 3 import java.time.ZoneId; 4 5 /** 6 * LocalDate Examples 7 * 8 * @author pankaj 9 * 10 */ 11 public class LocalDateExample 12 { 13 14 public static void main(String[] args) 15 { 16 17 // 当前日期 18 LocalDate today = LocalDate.now(); 19 System.out.println("当前日期=" + today); 20 21 // 通过传入的参数创建LocalDate对象 22 LocalDate firstDay_2014 = LocalDate.of(2014, Month.JANUARY, 1); 23 System.out.println("指定日期=" + firstDay_2014); 24 25 // 根据有效输入创建日期,以下代码会抛异常,无效输入,2014年2月没有29日 26 // LocalDate feb29_2014 = LocalDate.of(2014, Month.FEBRUARY, 29); 27 // Exception in thread "main" java.time.DateTimeException: 28 // Invalid date ‘February 29‘ as ‘2014‘ is not a leap year 29 30 // 获取不同时区的日期 "Asia/Kolkata", you can get it from ZoneId javadoc 31 LocalDate todayKolkata = LocalDate.now(ZoneId.of("Asia/Kolkata")); 32 System.out.println("当前印度标准日期=" + todayKolkata); 33 34 // java.time.zone.ZoneRulesException: Unknown time-zone ID: IST 35 // LocalDate todayIST = LocalDate.now(ZoneId.of("IST")); 36 37 // 从基准日期获取日期 例如: 01/01/1970 38 LocalDate dateFromBase = LocalDate.ofEpochDay(365); 39 System.out.println("基准日期的第365天= " + dateFromBase); 40 41 //2014年的第一百天 42 LocalDate hundredDay2014 = LocalDate.ofYearDay(2014, 100); 43 System.out.println("2014年的第一百天=" + hundredDay2014); 44 } 45 46 }
示例方法的详解都包含在注释内,当我们运行程序时,可以得到以下输出:
当前日期=2016-10-17 指定日期=2014-01-01 当前印度标准日期=2016-10-17 基准日期的第365天= 1971-01-01 2014年的第一百天=2014-04-10
LocalTime是一个不可变的类,它的实例代表一个符合人类可读格式的时间,默认格式是hh:mm:ss.zzz。像LocalDate一样,该类也提供了时区支持,同时也可以传入小时、分钟和秒等输入参数创建实例,我们来看一个简单的程序,演示该类的使用方法。
1 import java.time.LocalTime; 2 import java.time.ZoneId; 3 4 /** 5 * LocalTime Examples 6 * 7 * @author pankaj 8 * 9 */ 10 public class LocalTimeExample 11 { 12 13 public static void main(String[] args) 14 { 15 16 // Current Time 17 LocalTime time = LocalTime.now(); 18 System.out.println("Current Time=" + time); 19 20 // Creating LocalTime by providing input arguments 21 LocalTime specificTime = LocalTime.of(12, 20, 25, 40); 22 System.out.println("Specific Time of Day=" + specificTime); 23 24 // Try creating time by providing invalid inputs 25 // LocalTime invalidTime = LocalTime.of(25,20); 26 // Exception in thread "main" java.time.DateTimeException: 27 // Invalid value for HourOfDay (valid values 0 - 23): 25 28 29 // Current date in "Asia/Kolkata", you can get it from ZoneId javadoc 30 LocalTime timeKolkata = LocalTime.now(ZoneId.of("Asia/Kolkata")); 31 System.out.println("Current Time in IST=" + timeKolkata); 32 33 // java.time.zone.ZoneRulesException: Unknown time-zone ID: IST 34 // LocalTime todayIST = LocalTime.now(ZoneId.of("IST")); 35 36 // Getting date from the base date i.e 01/01/1970 37 LocalTime specificSecondTime = LocalTime.ofSecondOfDay(10000); 38 System.out.println("10000th second time= " + specificSecondTime); 39 40 } 41 42 }
当运行以上程序时,可以看到如下输出:
1 Current Time=16:19:00.232 2 Specific Time of Day=12:20:25.000000040 3 Current Time in IST=13:49:00.233 4 10000th second time= 02:46:40
LocalDateTime是一个不可变的日期-时间对象,它表示一组日期-时间,默认格式是yyyy-MM-dd-HH-mm-ss.zzz。它提供了一个工厂方法,通过接收LocalDate和LocalTime输入参数,来创建LocalDateTime实例。我们来看一个简单的例子。
1 import java.time.LocalDate; 2 import java.time.LocalDateTime; 3 import java.time.LocalTime; 4 import java.time.Month; 5 import java.time.ZoneId; 6 import java.time.ZoneOffset; 7 8 public class LocalDateTimeExample 9 { 10 11 public static void main(String[] args) 12 { 13 14 // Current Date 15 LocalDateTime today = LocalDateTime.now(); 16 System.out.println("Current DateTime=" + today); 17 18 // Current Date using LocalDate and LocalTime 19 today = LocalDateTime.of(LocalDate.now(), LocalTime.now()); 20 System.out.println("Current DateTime=" + today); 21 22 // Creating LocalDateTime by providing input arguments 23 LocalDateTime specificDate = LocalDateTime.of(2014, Month.JANUARY, 1, 10, 10, 30); 24 System.out.println("Specific Date=" + specificDate); 25 26 // Try creating date by providing invalid inputs 27 // LocalDateTime feb29_2014 = LocalDateTime.of(2014, Month.FEBRUARY, 28, 28 // 25,1,1); 29 // Exception in thread "main" java.time.DateTimeException: 30 // Invalid value for HourOfDay (valid values 0 - 23): 25 31 32 // Current date in "Asia/Kolkata", you can get it from ZoneId javadoc 33 LocalDateTime todayKolkata = LocalDateTime.now(ZoneId.of("Asia/Kolkata")); 34 System.out.println("Current Date in IST=" + todayKolkata); 35 36 // java.time.zone.ZoneRulesException: Unknown time-zone ID: IST 37 // LocalDateTime todayIST = LocalDateTime.now(ZoneId.of("IST")); 38 39 // Getting date from the base date i.e 01/01/1970 40 LocalDateTime dateFromBase = LocalDateTime.ofEpochSecond(10000, 0, ZoneOffset.UTC); 41 System.out.println("10000th second time from 01/01/1970= " + dateFromBase); 42 43 } 44 45 }
在所有这三个例子中,我们已经看到如果我们提供了无效的参数去创建日期/时间,那么系统会抛出java.time.DateTimeException,这是一种运行时异常,我们并不需要显式地捕获它。同时我们也看到,能够通过传入ZoneId得到日期/时间数据,你可以从它的Javadoc中得到支持的Zoneid的列表,当运行以上类时,可以得到以下输出:
Current DateTime=2016-10-17T16:22:19.453 Current DateTime=2016-10-17T16:22:19.453 Specific Date=2014-01-01T10:10:30 Current Date in IST=2016-10-17T13:52:19.454 10000th second time from 01/01/1970= 1970-01-01T02:46:40
Instant类是用在机器可读的时间格式上的,它以Unix时间戳的形式存储日期时间,我们来看一个简单的程序。
1 import java.time.Duration; 2 import java.time.Instant; 3 4 public class InstantExample 5 { 6 7 public static void main(String[] args) 8 { 9 // Current timestamp 10 Instant timestamp = Instant.now(); 11 System.out.println("Current Timestamp = " + timestamp); 12 13 // Instant from timestamp 14 Instant specificTime = Instant.ofEpochMilli(timestamp.toEpochMilli()); 15 System.out.println("Specific Time = " + specificTime); 16 17 // Duration example 18 Duration thirtyDay = Duration.ofDays(30); 19 System.out.println(thirtyDay); 20 } 21 22 }
输出结果:
Current Timestamp = 2016-10-17T08:25:08.069Z Specific Time = 2016-10-17T08:25:08.069Z PT720H
我们早些时候提到过,大多数日期/时间API类都实现了一系列工具方法,如:加/减天数、周数、月份数,等等。还有其他的工具方法能够使用TemporalAdjuster调整日期,并计算两个日期间的周期。
1 import java.time.LocalDate; 2 import java.time.LocalTime; 3 import java.time.Period; 4 import java.time.temporal.TemporalAdjusters; 5 6 public class DateAPIUtilities 7 { 8 9 public static void main(String[] args) 10 { 11 12 LocalDate today = LocalDate.now(); 13 14 // Get the Year, check if it‘s leap year 15 System.out.println("Year " + today.getYear() + " is Leap Year? " + today.isLeapYear()); 16 17 // Compare two LocalDate for before and after 18 System.out.println("Today is before 01/01/2015? " + today.isBefore(LocalDate.of(2015, 1, 1))); 19 20 // Create LocalDateTime from LocalDate 21 System.out.println("Current Time=" + today.atTime(LocalTime.now())); 22 23 // plus and minus operations 24 System.out.println("10 days after today will be " + today.plusDays(10)); 25 System.out.println("3 weeks after today will be " + today.plusWeeks(3)); 26 System.out.println("20 months after today will be " + today.plusMonths(20)); 27 28 System.out.println("10 days before today will be " + today.minusDays(10)); 29 System.out.println("3 weeks before today will be " + today.minusWeeks(3)); 30 System.out.println("20 months before today will be " + today.minusMonths(20)); 31 32 // Temporal adjusters for adjusting the dates 33 System.out.println("First date of this month= " + today.with(TemporalAdjusters.firstDayOfMonth())); 34 LocalDate lastDayOfYear = today.with(TemporalAdjusters.lastDayOfYear()); 35 System.out.println("Last date of this year= " + lastDayOfYear); 36 37 Period period = today.until(lastDayOfYear); 38 System.out.println("Period Format= " + period); 39 System.out.println("Months remaining in the year= " + period.getMonths()); 40 } 41 }
输出结果:
Year 2016 is Leap Year? true Today is before 01/01/2015? false Current Time=2016-10-17T16:30:30.743 10 days after today will be 2016-10-27 3 weeks after today will be 2016-11-07 20 months after today will be 2018-06-17 10 days before today will be 2016-10-07 3 weeks before today will be 2016-09-26 20 months before today will be 2015-02-17 First date of this month= 2016-10-01 Last date of this year= 2016-12-31 Period Format= P2M14D Months remaining in the year= 2
将一个日期格式转换为不同的格式,之后再解析一个字符串,得到日期时间对象,这些都是很常见的。我们来看一下简单的例子。
1 import java.time.Instant; 2 import java.time.LocalDate; 3 import java.time.LocalDateTime; 4 import java.time.format.DateTimeFormatter; 5 6 public class DateParseFormatExample 7 { 8 9 public static void main(String[] args) 10 { 11 12 // Format examples 13 LocalDate date = LocalDate.now(); 14 // default format 15 System.out.println("Default format of LocalDate=" + date); 16 // specific format 17 System.out.println(date.format(DateTimeFormatter.ofPattern("d::MMM::uuuu"))); 18 System.out.println(date.format(DateTimeFormatter.BASIC_ISO_DATE)); 19 20 LocalDateTime dateTime = LocalDateTime.now(); 21 // default format 22 System.out.println("Default format of LocalDateTime=" + dateTime); 23 // specific format 24 System.out.println(dateTime.format(DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss"))); 25 System.out.println(dateTime.format(DateTimeFormatter.BASIC_ISO_DATE)); 26 27 Instant timestamp = Instant.now(); 28 // default format 29 System.out.println("Default format of Instant=" + timestamp); 30 31 // Parse examples 32 LocalDateTime dt = LocalDateTime.parse("27::四月::2014 21::39::48", 33 DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss")); 34 System.out.println("Default format after parsing = " + dt); 35 } 36 37 }
输出结果:
Default format of LocalDate=2016-10-17 17::十月::2016 20161017 Default format of LocalDateTime=2016-10-17T16:37:47.846 17::十月::2016 16::37::47 20161017 Default format of Instant=2016-10-17T08:37:47.847Z Default format after parsing = 2014-04-27T21:39:48
旧的日期/时间类已经在几乎所有的应用程序中使用,因此做到向下兼容是必须的。这也是为什么会有若干工具方法帮助我们将旧的类转换为新的类,反之亦然。我们来看一下简单的例子。
1 import java.time.Instant; 2 import java.time.LocalDateTime; 3 import java.time.ZoneId; 4 import java.time.ZonedDateTime; 5 import java.util.Calendar; 6 import java.util.Date; 7 import java.util.GregorianCalendar; 8 import java.util.TimeZone; 9 10 public class DateAPILegacySupport 11 { 12 13 public static void main(String[] args) 14 { 15 16 // Date to Instant 17 Instant timestamp = new Date().toInstant(); 18 // Now we can convert Instant to LocalDateTime or other similar classes 19 LocalDateTime date = LocalDateTime.ofInstant(timestamp, 20 ZoneId.of(ZoneId.SHORT_IDS.get("PST"))); 21 System.out.println("Date = " + date); 22 23 // Calendar to Instant 24 Instant time = Calendar.getInstance().toInstant(); 25 System.out.println(time); 26 // TimeZone to ZoneId 27 ZoneId defaultZone = TimeZone.getDefault().toZoneId(); 28 System.out.println(defaultZone); 29 30 // ZonedDateTime from specific Calendar 31 ZonedDateTime gregorianCalendarDateTime = new GregorianCalendar().toZonedDateTime(); 32 System.out.println(gregorianCalendarDateTime); 33 34 // Date API to Legacy classes 35 Date dt = Date.from(Instant.now()); 36 System.out.println(dt); 37 38 TimeZone tz = TimeZone.getTimeZone(defaultZone); 39 System.out.println(tz); 40 41 GregorianCalendar gc = GregorianCalendar.from(gregorianCalendarDateTime); 42 System.out.println(gc); 43 44 } 45 46 }
输出结果:
ate = 2016-10-17T01:39:34.121 2016-10-17T08:39:34.176Z Asia/Shanghai 2016-10-17T16:39:34.191+08:00[Asia/Shanghai] Mon Oct 17 16:39:34 CST 2016 sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=19,lastRule=null] java.util.GregorianCalendar[time=1476693574191,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=19,lastRule=null],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2016,MONTH=9,WEEK_OF_YEAR=42,WEEK_OF_MONTH=3,DAY_OF_MONTH=17,DAY_OF_YEAR=291,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=4,HOUR_OF_DAY=16,MINUTE=39,SECOND=34,MILLISECOND=191,ZONE_OFFSET=28800000,DST_OFFSET=0]
你可以看到,旧的TimeZone和GregorianCalendar类的toString()方法太啰嗦了,一点都不友好。
这就是所有的Java 8 日期/时间API的内容,我非常喜欢这个API,它易于使用,同时它采取了某项工作,使相似的方法也易于寻找,虽然从旧的类转移到新的日期时间类需要消耗一定的时间,但我相信这是值得的。
转载: 风一样的码农 http://www.cnblogs.com/chenpi/
原文链接: journaldev 翻译: ImportNew.com - Justin Wu
译文链接: http://www.importnew.com/14140.html
【转】JAVA 8 日期/时间(Date/Time)API指南
原文:https://www.cnblogs.com/zhongjunbo555/p/11274026.html