Java的时间与日期处理

  Java 8以前采用:1.java.util.Date类        

                                      Date date=new Date();
                                      System.out.println(date);//打印系统当前时间 Fri Aug 31 16:49:34 CST 2018

                              2.java.util.Calender类

                                      Calendar calendar=Calendar.getInstance();
                                      int year=calendar.get(Calendar.YEAR);
                                      int month=calendar.get(Calendar.MONTH);
                                      int day=calendar.get(Calendar.DAY_OF_MONTH);
                                      System.out.println(year + "-" + (month + 1) + "-" + day);//打印系统当前时间 2018-8-31

    缺点:Date类起始年份是1900年,月份从0开始;Calendar月份依旧是从0开始计算;Date和Calendar类都是可变的

   Java 8以后采用:1.日期采用 java.time.LocalDate;时间采用java.time.LocalTime;合并时间与日期采用LocalDateTime

                                      LocalDate ofDate1=LocalDate.of(2018, 8, 31);//创建
                                      LocalTime ofTime=LocalTime.of(16, 56,30);//创建

                                      LocalDate parseDate=LocalDate.parse("2018-08-31");//创建
                                      LocalTime parseTime=LocalTime.parse("16:56:30");//创建

                                      LocalDateTime dt1 = LocalDateTime.of(2018, Month.MARCH, 31, 13, 45, 20);//创建
                                      LocalDateTime dt2 = LocalDateTime.of(ofDate1, ofTime);//创建

                                 2.格式化日期采用java.time.format.DateTimeFormatter

                                     String s1 = ofDate1.format(DateTimeFormatter.BASIC_ISO_DATE);
                                     System.out.println(s1);//20180831

                                     String s2 = ofDate1.format(DateTimeFormatter.ISO_LOCAL_DATE);
                                     System.out.println(s2);//2018-08-31

                                     DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");//设置特定格式
                                     String s3 = ofDate1.format(formatter);
                                     System.out.println(s3);//31/08/2018

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值