java中日期和时间相关类(包括java8中新增java.time包)
来源:互联网 发布:usb网络共享驱动下载 编辑:程序博客网 时间:2024/05/22 12:56
一.ava8之前的日期时间相关类
1.java8之前所有日期时间相关类图(箭头的意思是:父类—->子类)(具体方法见API)
2.Date类
(1)标准java类库中包含一个Date类,它的对象表示一个特定的瞬间(时刻,时间点),精确到毫秒
(2)Date类中封装了一个long型值,用Date类其实是用这个数字来表示时间,是从:标准纪元1970.1.1的0点开始到某个时刻的毫秒数,类型是long
(3)类内相关方法,有很多遗弃方法转移到了calendar类中,格式转换方法转移到了DateFormat类中
3.DateFormat类(这是抽象类)和SimpleDateFromat类(这是具体的实现类)
(1)作用:按照指定格式,完成字符串和时间对象的相互转换
(2)用法:
- 将时间对象按照格式化字符串,转换成特定格式的字符串
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");Date d = new Date(111111111L);String str = df.format(d);
- 将特定格式的字符串转换成时间对象
注意:
调用SimpleDateFormat对象的parse()方法时可能会出现转换异常,即ParseException,因此需要进行异常处理
DateFormat类和SimpleDateFormat类都不是线程安全的,使用是要小心
String str = "1995-01-27";DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");try { Date d2 = df2.parse(str);} catch (ParseException e) { e.printStackTrace();}
4.Calendar类(这是抽象类)和GregorianCalendar类(这是具体的实现类)
(1)抽象类Calendar提供了一组方法,允许把以毫秒为单位的时间转换成一些有用的时间组成部分。Calendar 不能直接创建对象,但可以使用静态方法 getInstance() 获得代表当前日期的日历对象
(2)GregorianCalendar提供了世界上大多数地区使用的标准日历系统(正常 Gregorian 公历的实现)
(3)注意:
- 月份:一月是0.二月是1,三月是2……十二月是11
- 星期:周日是1,周一是2,周三是3……周六是7
(4)作用(用来解释和处理Date类):
- 完成时刻(Date类中的那个Long值)与日期间(类似某年某月某日某时某分某秒)的相互转换
- 日期计算
public class TimeTest { public static void main(String[] args) { Calendar c = new GregorianCalendar(); //设置具体时间 c.set(1995, 1, 27, 2, 23,15); //或者使用下面的设置方法 c.set(Calendar.YEAR, 1995); c.set(Calendar.MONTH, 1); //或者使用下面的设置方法 c.setTime(new Date()); Date d = c.getTime(); //Calendar和Date的转换 System.out.println(d); //日期计算 c.add(Calendar.MONTH, 12); System.out.println(c); }}
二.java8新增的java.time包(JSR310 Java Date与Time API)
1.为什么需要新的java日期/时间API(原日期/时间类的缺点)
(1)命名: Java的Date/Calendar类的定义与名称并不一致,Date 不是“日期”,而 Calendar 也不是“日历”,在java.util和java.sql的包中都有日期类,此外用于格式化和解析的类在java.text包中定义。java.util.Date同时包含日期和时间,而java.sql.Date仅包含日期,将其纳入java.sql包并不合理。另外这两个类都有相同的名字,这本身就是一个非常糟糕的设计。
(2)可变性:Date类并不提供国际化,没有时区支持,因此Java引入了java.util.Calendar和java.util.TimeZone类,但是这三个类中的所有属性都是可变的,是线程不安全的.像这样的类应该是不可变的
(3)偏移性:Date 中的月份与小时都是基于0,月份中的天数则是基于1,而年则是从1900开始的,很混乱
(4)格式化:java.text.DateFormat格式化只对 Date 有用, Calendar 则不行,而且它也是线程不安全的
2.JSR310的优点
(1)不变性:新的日期/时间API中,所有的类都是不可变的,这对多线程环境有好处。
(2)关注点分离:新的API将人可读的日期时间和机器时间(unix timestamp)明确分离,它为日期(Date)、时间(Time)、日期时间(DateTime)、时间戳(unix timestamp)以及时区定义了不同的类。
(3)清晰:在所有的类中,方法都被明确定义用以完成相同的行为。举个例子,要拿到当前实例我们可以使用now()方法,在所有的类中都定义了format()和parse()方法,而不是像以前那样专门有一个独立的类。为了更好的处理问题,所有的类都使用了工厂模式和策略模式,一旦你使用了其中某个类的方法,与其他类协同工作并不困难。
(4)实用操作:所有新的日期/时间API类都实现了一系列方法用以完成通用的任务,如:加、减、格式化、解析、从日期/时间中提取单独部分,等等。
(5)可扩展性:新的日期/时间API是工作在ISO-8601日历系统上的,但我们也可以将其应用在非ISO的日历上。
3.JSR 310实际上有两个日期概念。第一个是Instant,它大致对应于java.util.Date类,因为它代表了一个确定的时间点,即相对于标准Java纪元(1970年1月1日)的偏移量;但与java.util.Date类不同的是其精确到了纳秒级别。
第二个对应于人类自身的观念,比如LocalDate和LocalTime。他们代表了一般的时区概念,要么是日期(不包含时间),要么是时间(不包含日期),类似于java.sql的表示方式。此外,还有一个MonthDay,它可以存储某人的生日(不包含年份)。每个类都在内部存储正确的数据而不是像java.util.Date那样利用午夜12点来区分日期,利用1970-01-01来表示时间。
4.JSR310 Java Date与Time API由5个包组成
(1)java.time包:这是新的Java日期/时间API的基础包,所有的主要基础类都是这个包的一部分,如:LocalDate, LocalTime, LocalDateTime, Instant, Period, Duration等等。所有这些类都是不可变的和线程安全的,在绝大多数情况下,这些类能够有效地处理一些公共的需求。
(2)java.time.chrono包:这个包为非ISO的日历系统定义了一些泛化的API,我们可以扩展AbstractChronology类来创建自己的日历系统。
(3)java.time.format包:这个包包含能够格式化和解析日期时间对象的类,在绝大多数情况下,我们不应该直接使用它们,因为java.time包中相应的类已经提供了格式化和解析的方法。
(4)java.time.temporal包:这个包包含一些时态对象,我们可以用其找出关于日期/时间对象的某个特定日期或时间,比如说,可以找到某月的第一天或最后一天。你可以非常容易地认出这些方法,因为它们都具有“withXXX”的格式。
(5)java.time.zone包:这个包包含支持不同时区以及相关规则的类。
5.一些常用类的用法(具体还是看API自己动手吧)
(1)Instant—-Instant类是用在机器可读的时间格式上的.表示时间线上的一个瞬间(也就是时间点)。在Java7的date time API中,一个瞬间通常由从1970年1月1日到现在的总毫秒数来表示。在Java8中Instant类代表着时间线上的一个瞬间,这个瞬间由从1970年1月1日到现在的总秒数和总纳秒数来表示。
public class InstantExample { public static void main(String[] args) { //Current timestamp Instant timestamp = Instant.now(); System.out.println("Current Timestamp = "+timestamp); //Instant from timestamp Instant specificTime = Instant.ofEpochMilli(timestamp.toEpochMilli()); System.out.println("Specific Time = "+specificTime); //Duration example Duration thirtyDay = Duration.ofDays(30); System.out.println(thirtyDay); }}
输出结果:
Current Timestamp = 2014-04-28T23:20:08.489Z
Specific Time = 2014-04-28T23:20:08.489Z
PT720H
(2)LocalDate—-表示不带时区信息(但可以传入ZoneId来获得指定时区的日期)的日期,默认格式为(yyyy-MM-dd)
public class LocalDateExample { public static void main(String[] args) { //Current Date LocalDate today = LocalDate.now(); System.out.println("Current Date="+today); //Creating LocalDate by providing input arguments LocalDate firstDay_2014 = LocalDate.of(2014, Month.JANUARY, 1); System.out.println("Specific Date="+firstDay_2014); //Try creating date by providing invalid inputs //LocalDate feb29_2014 = LocalDate.of(2014, Month.FEBRUARY, 29); //Exception in thread "main" java.time.DateTimeException: //Invalid date 'February 29' as '2014' is not a leap year //Current date in "Asia/Kolkata", you can get it from ZoneId javadoc LocalDate todayKolkata = LocalDate.now(ZoneId.of("Asia/Kolkata")); System.out.println("Current Date in IST="+todayKolkata); //java.time.zone.ZoneRulesException: Unknown time-zone ID: IST //LocalDate todayIST = LocalDate.now(ZoneId.of("IST")); //Getting date from the base date i.e 01/01/1970 LocalDate dateFromBase = LocalDate.ofEpochDay(365); System.out.println("365th day from base date= "+dateFromBase); LocalDate hundredDay2014 = LocalDate.ofYearDay(2014, 100); System.out.println("100th day of 2014="+hundredDay2014); }}
输出结果:
Current Date=2014-04-28
Specific Date=2014-01-01
Current Date in IST=2014-04-29
365th day from base date= 1971-01-01
100th day of 2014=2014-04-10
(3)LocalTime—-表示不带时区信息(但可以传入ZoneId来获得指定时区的日期)的时间,默认格式是hh:mm:ss.zzz
public class LocalTimeExample { public static void main(String[] args) { //Current Time LocalTime time = LocalTime.now(); System.out.println("Current Time="+time); //Creating LocalTime by providing input arguments LocalTime specificTime = LocalTime.of(12,20,25,40); System.out.println("Specific Time of Day="+specificTime); //Try creating time by providing invalid inputs //LocalTime invalidTime = LocalTime.of(25,20); //Exception in thread "main" java.time.DateTimeException: //Invalid value for HourOfDay (valid values 0 - 23): 25 //Current date in "Asia/Kolkata", you can get it from ZoneId javadoc LocalTime timeKolkata = LocalTime.now(ZoneId.of("Asia/Kolkata")); System.out.println("Current Time in IST="+timeKolkata); //java.time.zone.ZoneRulesException: Unknown time-zone ID: IST //LocalTime todayIST = LocalTime.now(ZoneId.of("IST")); //Getting date from the base date i.e 01/01/1970 LocalTime specificSecondTime = LocalTime.ofSecondOfDay(10000); System.out.println("10000th second time= "+specificSecondTime); }}
输出结果:
Current Time=15:51:45.240
Specific Time of Day=12:20:25.000000040
Current Time in IST=04:21:45.276
10000th second time= 02:46:40
(4)LocalDateTime—-表示不带时区信息的日期时间。默认格式是yyyy-MM-dd-HH-mm-ss.zzz.这个类只是 LocalDate 和 LocalTime 的简单组合.
public class LocalDateTimeExample { public static void main(String[] args) { //Current Date LocalDateTime today = LocalDateTime.now(); System.out.println("Current DateTime="+today); //Current Date using LocalDate and LocalTime today = LocalDateTime.of(LocalDate.now(), LocalTime.now()); System.out.println("Current DateTime="+today); //Creating LocalDateTime by providing input arguments LocalDateTime specificDate = LocalDateTime.of(2014, Month.JANUARY, 1, 10, 10, 30); System.out.println("Specific Date="+specificDate); //Try creating date by providing invalid inputs //LocalDateTime feb29_2014 = LocalDateTime.of(2014, Month.FEBRUARY, 28, 25,1,1); //Exception in thread "main" java.time.DateTimeException: //Invalid value for HourOfDay (valid values 0 - 23): 25 //Current date in "Asia/Kolkata", you can get it from ZoneId javadoc LocalDateTime todayKolkata = LocalDateTime.now(ZoneId.of("Asia/Kolkata")); System.out.println("Current Date in IST="+todayKolkata); //java.time.zone.ZoneRulesException: Unknown time-zone ID: IST //LocalDateTime todayIST = LocalDateTime.now(ZoneId.of("IST")); //Getting date from the base date i.e 01/01/1970 LocalDateTime dateFromBase = LocalDateTime.ofEpochSecond(10000, 0, ZoneOffset.UTC); System.out.println("10000th second time from 01/01/1970= "+dateFromBase); }}
输出结果:
Current DateTime=2014-04-28T16:00:49.455
Current DateTime=2014-04-28T16:00:49.493
Specific Date=2014-01-01T10:10:30
Current Date in IST=2014-04-29T04:30:49.493
10000th second time from 01/01/1970= 1970-01-01T02:46:40
(5)TemporalAdjuster—-时间修改器
public class DateAPIUtilities { public static void main(String[] args) { LocalDate today = LocalDate.now(); //Get the Year, check if it's leap year System.out.println("Year "+today.getYear()+" is Leap Year? "+today.isLeapYear()); //Compare two LocalDate for before and after System.out.println("Today is before 01/01/2015? "+today.isBefore(LocalDate.of(2015,1,1))); //Create LocalDateTime from LocalDate System.out.println("Current Time="+today.atTime(LocalTime.now())); //plus and minus operations System.out.println("10 days after today will be "+today.plusDays(10)); System.out.println("3 weeks after today will be "+today.plusWeeks(3)); System.out.println("20 months after today will be "+today.plusMonths(20)); System.out.println("10 days before today will be "+today.minusDays(10)); System.out.println("3 weeks before today will be "+today.minusWeeks(3)); System.out.println("20 months before today will be "+today.minusMonths(20)); //Temporal adjusters for adjusting the dates System.out.println("First date of this month= "+today.with(TemporalAdjusters.firstDayOfMonth())); LocalDate lastDayOfYear = today.with(TemporalAdjusters.lastDayOfYear()); System.out.println("Last date of this year= "+lastDayOfYear); Period period = today.until(lastDayOfYear); System.out.println("Period Format= "+period); System.out.println("Months remaining in the year= "+period.getMonths()); }}
输出结果:
Year 2014 is Leap Year? false
Today is before 01/01/2015? true
Current Time=2014-04-28T16:23:53.154
10 days after today will be 2014-05-08
3 weeks after today will be 2014-05-19
20 months after today will be 2015-12-28
10 days before today will be 2014-04-18
3 weeks before today will be 2014-04-07
20 months before today will be 2012-08-28
First date of this month= 2014-04-01
Last date of this year= 2014-12-31
Period Format= P8M3D
Months remaining in the year= 8
(6)ZoneId—-可用来进行Instant和LocalDateTime的互相转换
(7)ZonedDateTime—-表示携带时区信息的日期时间
(8)Duration—-表示以时、分、秒、纳秒为基准的时长(持续时间).例如:12.6秒,22分钟
(9)Period—-表示以年、月、日为基准的时长(持续时间).例如:1年2个月零4天
(10)DateTimeFormatter—-将datetime对象格式化为字符串。比如zonedDateTime或者LocalDateTime
public class DateParseFormatExample { public static void main(String[] args) { //Format examples LocalDate date = LocalDate.now(); //default format System.out.println("Default format of LocalDate="+date); //specific format System.out.println(date.format(DateTimeFormatter.ofPattern("d::MMM::uuuu"))); System.out.println(date.format(DateTimeFormatter.BASIC_ISO_DATE)); LocalDateTime dateTime = LocalDateTime.now(); //default format System.out.println("Default format of LocalDateTime="+dateTime); //specific format System.out.println(dateTime.format(DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss"))); System.out.println(dateTime.format(DateTimeFormatter.BASIC_ISO_DATE)); Instant timestamp = Instant.now(); //default format System.out.println("Default format of Instant="+timestamp); //Parse examples LocalDateTime dt = LocalDateTime.parse("27::Apr::2014 21::39::48", DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss")); System.out.println("Default format after parsing = "+dt); }}
输出结果:
Default format of LocalDate=2014-04-28
28::Apr::2014
20140428
Default format of LocalDateTime=2014-04-28T16:25:49.341
28::Apr::2014 16::25::49
20140428
Default format of Instant=2014-04-28T23:25:49.342Z
Default format after parsing = 2014-04-27T21:39:48
(11)的日期时间支持:旧的日期/时间类已经在几乎所有的应用程序中使用,因此做到向下兼容是必须的。这也是为什么会有若干工具方法帮助我们将旧的类转换为新的类,反之亦然。
public class DateAPILegacySupport { public static void main(String[] args) { //Date to Instant Instant timestamp = new Date().toInstant(); //Now we can convert Instant to LocalDateTime or other similar classes LocalDateTime date = LocalDateTime.ofInstant(timestamp, ZoneId.of(ZoneId.SHORT_IDS.get("PST"))); System.out.println("Date = "+date); //Calendar to Instant Instant time = Calendar.getInstance().toInstant(); System.out.println(time); //TimeZone to ZoneId ZoneId defaultZone = TimeZone.getDefault().toZoneId(); System.out.println(defaultZone); //ZonedDateTime from specific Calendar ZonedDateTime gregorianCalendarDateTime = new GregorianCalendar().toZonedDateTime(); System.out.println(gregorianCalendarDateTime); //Date API to Legacy classes Date dt = Date.from(Instant.now()); System.out.println(dt); TimeZone tz = TimeZone.getTimeZone(defaultZone); System.out.println(tz); GregorianCalendar gc = GregorianCalendar.from(gregorianCalendarDateTime); System.out.println(gc); }}
输出结果:
Date = 2014-04-28T16:28:54.3402014-04-28T23:28:54.395ZAmerica/Los_Angeles2014-04-28T16:28:54.404-07:00[America/Los_Angeles]Mon Apr 28 16:28:54 PDT 2014sun.util.calendar.ZoneInfo[id="America/Los_Angeles",offset=-28800000,dstSavings=3600000,useDaylight=true,transitions=185,lastRule=java.util.SimpleTimeZone[id=America/Los_Angeles,offset=-28800000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]]java.util.GregorianCalendar[time=1398727734404,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/Los_Angeles",offset=-28800000,dstSavings=3600000,useDaylight=true,transitions=185,lastRule=java.util.SimpleTimeZone[id=America/Los_Angeles,offset=-28800000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2014,MONTH=3,WEEK_OF_YEAR=18,WEEK_OF_MONTH=5,DAY_OF_MONTH=28,DAY_OF_YEAR=118,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=4,AM_PM=1,HOUR=4,HOUR_OF_DAY=16,MINUTE=28,SECOND=54,MILLISECOND=404,ZONE_OFFSET=-28800000,DST_OFFSET=3600000]
6.总结一般方法前缀:
- of: 静态工厂方法,从组成部分中创建实例
- from: 静态工厂方法,尝试从相似对象中提取实例。from()方法没有of()方法类型安全
- now: 静态工厂方法,用当前时间创建实例
- parse: 静态工厂方法,总字符串解析得到对象实例
- get: 获取时间日期对象的部分状态
- is: 检查关于时间日期对象的描述是否正确
- with: 返回一个部分状态改变了的时间日期对象拷贝
- plus: 返回一个时间增加了的、时间日期对象拷贝
- minus: 返回一个时间减少了的、时间日期对象拷贝
- to: 把当前时间日期对象转换成另外一个,可能会损失部分状态
- at: 用当前时间日期对象组合另外一个,创建一个更大或更复杂的时间日期对象
- format: 提供格式化时间日期对象的能力
- java中日期和时间相关类(包括java8中新增java.time包)
- java中日期和时间
- Java中日期与时间相关类用法解析
- Java中日期时间
- java中日期和时间的处理
- JAVA中日期和时间的比较
- java中日期的格式化 时间类
- Java中日期时间比较
- Java中日期类
- java集合(包括java8新增知识)
- java8时间---java.time.LocalDate
- Java和Android中日期时间格式DateFormat
- Java中日期和时间的处理原理解析
- Java中日期和时间的处理原理解析
- java中日期相关部分转换
- Java中日期时间格式的小结
- Java中日期时间处理小结
- Java中日期时间的处理
- 7. HTTP 请求,响应
- Ubuntu操作入门(1)
- 烈焰遮天 cocos 手游mmo 源码 解析
- 学习笔记:mysql存储过程
- sqlplus修改oracle用户的密码和解锁用户
- java中日期和时间相关类(包括java8中新增java.time包)
- 【分享】找到一篇挺不错的面试题目
- java.lang.Math类
- 百度地图定位以及方向传感器的调用
- 百度地图的植入流程介绍
- equals和==号
- 顺序表的建立及增删查改
- 1053. Path of Equal Weight (30)-PAT甲级真题(树的遍历)
- 文章标题