本篇总结一下jdk8之前的日期处理方式,jdk8中新的日期处理以后用到总结。

package com.test; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date;  public class DateAndTime {     public static void main(String[] args) {          int year;         int month;         int day;          //老版本         Date date = new Date();         year = date.getYear()+1900;         month = date.getMonth()+1;         day = date.getDate();         System.out.println("老--"+year+"年"+month+"月"+day+"日");          //新版本         Calendar calendar = Calendar.getInstance();         year = calendar.get(Calendar.YEAR);         month = calendar.get(Calendar.MONTH)+1;         day = calendar.get(Calendar.DATE);         System.out.println("新--"+year+"年"+month+"月"+day+"日");          //毫秒数         long now = System.currentTimeMillis();         Date date2 = new Date(now);   //或 : date.setTime(now);   long-->Date         System.out.println(date2.getDate());          //时间类型转换 long <-> Date <-> Calendar         calendar.setTime(date2);     //                           Date-->Calendar         System.out.println(calendar.get(Calendar.YEAR));         calendar.getTime();          //                           Calendar-->Date         System.out.println(calendar.getTime().getDate());         date.getTime();         System.out.println(date.getTime());//                     Date-->long          //时间输入输出         SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");         String today = fmt.format(date2);                  //     Date-->String         try {             Date date3 = fmt.parse("2015-12-19 16:20:00"); //     String-->Date             System.out.println(date3);         } catch (ParseException e) {             e.printStackTrace();         }         System.out.println(today);          //利用Calendar时间计算         calendar.add(Calendar.YEAR, 2);         calendar.add(Calendar.MONTH, 1);         System.out.println(fmt.format(calendar.getTime()));//今天是2015年12月19号,这里应该是2018年1月19号         } } 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58

控制台打印如下:

--2015年12月19日 新--2015年12月19日 19 2015 19 1450513438352 Sat Dec 19 16:20:00 CST 2015 2015-12-19 16:23:58 2018-01-19 16:23:58 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10