java时间类API

一、jdk8之前的日期时间的API测试:

1.System了中currentTimeMIllis();//该方法的作用是返回当前的计算机时间,时间的表达格式为当前计算机时间和GMT时间(格林威治时间)1970年1月1号0时0分0秒所差的毫秒数。可以直接把这个方法强制转换成date类型。

public static long currentTimeMillis()

long currentTime = System.currentTimeMillis();

SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日,HH时mm分ss秒");

Date date = new Date(currentTime);

System.out.println(formatter.format(date));//2019年05月14天,19时09分13秒

 

2.java.util.Date和子类java.sql.Date   //返回当前日期,后者是兼容数据库类型的日期

  比如:给一个Date类的日期,可以先使用getTime()转化为毫秒数,然后作为参数传递给创建java.sql.Date的实例化作为参数,那么输出该实例化对象就是数据库兼容类型的日期。

3.simpleDateFormat  //对日期Date类的格式化和解析

  两个操作:

  >格式化:日期——>字符串

  

SimpleDateFormat s = new SimpleDateFormat();//实例化SimpleDateFormat
Date date = new Date();
System.out.println(format);
String format = s.format(date);
System.out.println(format);

  运行结果是这样的:

  

  >解析:格式化的逆过程:

  格式化需要严格对应格式,否则就会抛出异常。默认参数格式就是上面format输出格式,输出就是上面的date输出格式,但是一般来说都喜欢用我们自己看着舒服的格式,比如:

  

SimpleDateFormat s1 = new SimpleDateFormat(“yyy-MM-dd hh:mm:ss”);//实例化SimpleDateFormat
Date date = new Date();
String format = s1.format(date);
System.out.println(format);//2019-05-11 12:50:36

String str = “2019-05-11 12:50:36”
Date date1 = s1.parse(str);//解析
System.out.println(date1);//默认日期格式输出

4.calendar日历类(抽象类)

  4.1实例化的两种方式:

    >创建其子类(GregorianCalendar)的对象

    >调用其静态方法getInstance()获取对象(从源码上其实还是其子类的对象,只是子类难记,用一个方法简单一点)

  4.2常用的方法:

    >get():

int days = calendar.get(Calendar.DAY_OF_MONTH);//获取当前月份的第几天
System.out.println(calendar.get(Calendar.DAY_OF_YEAR));//获取当前年份的第几天

    >set():

calendar.set(Calendar.DAY_OF_MONTH,22);//将当前月份的第几天改成第22天

    >add():

calendar.add(Calendar.DAY_OF_MONTH,+/-3);//当前月份的第几天+/-3天

    >getTime():

Date date = calendar.getTime();//日历类——>Date

    >setTime():

Date date1 = new Date();
calendar.setTime(date1);//Date转化为日历类
days = calendar.get(Calendar.DAY_OF_MONTH);

输出结构就是以上截图的反着。

在这里其实可以看出来,8.0之前的时间日期API有很多问题要解决:

  • 可变性:像日期时间这样的类应该是不可变的,但是calendar却是没有返回值,直接修改本身。
  • 偏移性:Date中的年份是从1900年开始,而月份都是从0开始。
  • 格式化:格式化只对Date有用,而Calendar则不行。
  • 侧歪,它们线程不安全;不能处理闰秒等。

 

二、jdk8中新的时间日期API:

1.LocalDate(日期)、LocalTime(时间)、LocalDateTime(日期加时间)

以上这些新的方法就解决了Date和Calendar类的缺点。

用法举例:

LocalDate localDate = LocalDate.now();//获取当前的日期
LocalTime localTime = LocalTime .now();//获取当前的时间
LocalDateTime localDateTime = LocalDateTime.now();//获取当前的日期加时间

2.Instant(类比Date,记录毫秒数):

它的一些方法如下:

用法如下:

Instant instant = Instant.now();//获取本初子午线对应的标准时间,大概比北京时间早8个小时

OffsetDateTime offsetDateTime  = instant.atOffset(ZoneOffset.ofHours(8));//修改成北京时间

long milli = instant.toEpochMilli();//获取自1970年1月1日0时0分0秒(UTC)开始的毫秒数 ——>Date类的getTime()

Instant instant1 = Instant.ofEpochMilli(1550475314895L);//通过给定的毫秒数,获取Instant实例,输出为日期

 

 3.格式化与解析日期时间:

具体使用案例。参照上面的SimpleDateFormat用法。


 

posted @ 2019-05-11 18:43  黑暗之魂DarkSouls  阅读(313)  评论(0编辑  收藏  举报