Java 8 日期时间 Date / Time格式化

在Java 8之前,java.util.Date是非线程安全的;而Java 8 提供的LocalDate/LocalTime/LocalDateTime是不可变类且线程安全的

使用如下:

public static void main(String args[]){
        //get current date
        LocalDate localDate = LocalDate.now();
        System.out.println("当前日期 : "+localDate);//当前日期 : 2018-10-21
        //get current datetime
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println("当前时间 : "+localDateTime);//当前时间 : 2018-10-21T15:03:21.870
        //get current Month ; type Month
        Month month = localDateTime.getMonth();//print OCTOBER
//        Month month1 = localDate.getMonth();
        //get current Month ; type int
        int monthInt = month.getValue();//print 10
        //get day of month
        int day =  localDateTime.getDayOfMonth();//print 21
        //get day of year
        int day1 = localDateTime.getDayOfYear();//294
        //get seconds
        int seconds = localDateTime.getSecond();//21

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //datetime to String format "yyyy-MM-dd HH:mm:ss"
        String string = dateTimeFormatter.format(localDateTime);
        DateTimeFormatter dateTimeFormatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        //date to String format "yyyy-MM-dd"
        String string1 = dateTimeFormatter1.format(localDate);
        System.out.println("datetime : "+string+"  date : "+string1);//datetime : 2018-10-21 15:06:03  date : 2018-10-21
        //String to Date
        String tmp = "2018-09-21";
        String tmp1 = "2018-10-01 16:34:23";
        LocalDate localDate1 = LocalDate.parse(tmp,dateTimeFormatter1);
        LocalDateTime localDateTime1 = LocalDateTime.parse(tmp1,dateTimeFormatter);
        System.out.println("date : "+localDate1+"  datetime : "+localDateTime1);

        //get current zone
        ZoneId zoneId = ZoneId.systemDefault();
        System.out.println("Current Zone : "+zoneId);//Current Zone : Asia/Shanghai

        LocalDateTime localDateTime2 = localDateTime.withDayOfMonth(10).withYear(2017);
        System.out.println("localDateTime2 : "+localDateTime2);

        LocalDate localDate2 = LocalDate.of(2008,Month.NOVEMBER,11);//2008-11-11
        System.out.println("localDate2 : "+localDate2);

        LocalTime localTime = LocalTime.of(19,28);//19小时28分钟
        System.out.println("localTime : "+localTime);


    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值