java8时间类

java.time包中的类是不可变且是线程安全的。

下面是一些主要的时间类:

Instant:时间戳

LocalDate:不包含时间的日期

LocalTime:不包含日期的时间

LocalDateTime:包含日期及时间,没事时区

ZonedDateTime:包含日期及时间,偏移量是以UTC、格林威治时间为基准的

1.获取当日日期:

LocalDate localDate = LocalDate.now();  //2017-11-27
int year = localDate.getyear();         //获取年
int month = localDate.getMonthValue();  //获取月
int day = localDate.getDayOfMonth();    //获取日

2.获取输入日期

LocalDate localDate = LocalDate.of(1994,08,24);    //1994-08-24

3.日期的比较:

java8时间类重写equals()方法,可用于对比日期。

LocalDate localDate1 = LocalDate.of(1994,08,24);
LocalDate localDate2 = LocalDate.now();
localDate1.equals(localDate2);                   //false

4.获取日期当中的月日(MonthDay类):

重写了equals方法

MonthDay monthDay = MonthDay.now();
MonthDay monthDay1 = MonthDay.of(02.02);
MonthDay monthDay2 = MonthDay.parse("--08-24")     //--08-24
MonthDay monthDay3 = MonthDay.from(LocalDate.now());

5.时间的增加减少

增加和减少用法相同(plus:增加;minus:减少)

//使用plus**(Long i)来增加对应的时间数
public LocalTime plusHours(long hoursToAdd)         //增加小时
//也可通过plus()方法增加减少时间数
//amountToAdd:增加的数
//unit:对应的时间单位   例:ChronoUnit.Days  ->  增加天数
public LocalDate plus(long amountToAdd, TemporalUnit unit)

6.判断一个日期在另一个日期之前或之后

isAfter方法&isBefore方法

LocalDate today = LocalDate.now();
LocalDate tommorow = toDay.plus(1, Chronounit.DAYS);
tommorow.isAfter(today);                 //true
tommorow.isBefore(today);                //false

7.处理不同的时区

java8不仅对时间和日期进行了分离,也对时区进行了分离,ZoneId代表的是某个时区,ZonidLocalTime代表时区的时间,可以将本地时间转换为另一个时区的对应时间。

LocalDateTime localDateTime = LocalDateTime.now();   //本地时间
ZoneId zone = ZoneId.of(ZoneId.SHORT_IDS.get("ACT")); //时区
ZonedDateTime dateTimeInNewYork = ZoneIdDateTime.of(localDateTime,zone);//时区时间

8.表示固定的日期,比如信用卡过期时间

正如MonthDay表示的是某个重复出现的日子,YearMonth是另外一个组合,代表的是像信用卡还款日,定期存款到期日,options到期日这类的日期。你可以用这个类找出这个月有多少天,LengthOfMonth()这个方法返回的是这个YearMonth实例有多少天,这对于检查2月是否润2月很有用.

YearMonth yearMonth = YearMonth.now();
System.out.printf("本月一共有 %s 天%n",yearMonth.lengthOfMonth());
YearMonth yearMonth1 = YearMonth.of(2018,Month.AUGUST);
System.out.printf("2018年8月:%s",yearMonth1);

9.判断今年是否是闰年

LocalDate today = LocalDate.now();
System.out.printf("%s年是否是闰年:%s",today,today.isLeapYear());

猜你喜欢

转载自blog.csdn.net/asd104/article/details/80058574