Java -- 日期类-第一代-第二代-第三代日期
目录
1. 第一代日期类
2. 第二代日期类
3. 第三代日期
常见方法:
1. 使用now()返回表示当前日期时间的对象
2. 使用DateTimeFormatter 对象来进行格式化
3. Instant时间戳
4. 第三代日期类更多方法
1. 第一代日期类
Date:精确到毫秒,代表特定的瞬间
我们可以使用SimpleDateFormat对象,指定相应的格式
yyyy年MM月dd日 hh:mm:ss E
// 获取当前系统时间// 这里Date 指的是java.util包里的// 默认输出的日期格式是国外的方式 因此会对其进行格式转换Date d1 = new Date();System.out.println("当前日期:"+d1);//我们可以使用SimpleDateFormat对象,指定相应的格式// 格式的字母是规定好的,不能乱写SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss E");String format = sdf.format(d1);System.out.println("当前日期="+format);// 可以把一个格式化的字符串String转换成对应的Date// 得到Date仍然是在输出时,还是国外的格式 如果需要指定格式 通过SimpleDateFormat// 在把String -> Date ,使用的sdf格式需要和String一样
2. 第二代日期类
Calendar类(日历)
Calendar类是一个抽象类,它为特定瞬间与一组诸如YEAR,MONTH,DAY_OF_MONTH,HOUR等日历字段之间的转换提供了一些方法,并为操作日历字段(即获得下星期的日期)提供了一些方法。
// 是一个抽象类 并且构造器是private// 可以通过 getInstance()获取实例// 提供大量的方法和字段可使用Calendar c = Calendar.getInstance();//创建日历类对象System.out.println("c="+c);// 获取日历字段System.out.println("年:"+c.get(Calendar.YEAR));System.out.println("月:"+c.get(Calendar.MONTH)+1);System.out.println("日:"+c.get(Calendar.DAY_OF_MONTH));System.out.println("小时:"+c.get(Calendar.HOUR));System.out.println("分钟:"+c.get(Calendar.MINUTE));System.out.println("秒:"+c.get(Calendar.SECOND));
3. 第三代日期
常见方法:
1. LocalDate(日期/年月日),2. LocalTime(时间/时分秒),3. LocalDateTime(日期时间/年月日时分秒)
前俩代日期有不足的,Calendar存在问题:
1. 可变性:像日期和时间这样的类应该是不可变的。
2. 偏移性:Date中的年份是从1900开始的,而月份都从0开始
3. 格式化:格式化只对Date有用,Calendar不行。
4. 他们不是线程安全的,不能处理闰秒。
1. 使用now()返回表示当前日期时间的对象
LocalDateTime ldt = LocalDateTime.now();System.out.println(ldt);System.out.println("年="+ldt.getYear());System.out.println("月="+ldt.getMonth());System.out.println("月="+ldt.getMonthValue());System.out.println("日="+ldt.getDayOfMonth());System.out.println("时="+ldt.getHour());System.out.println("分="+ldt.getMinute());System.out.println("秒="+ldt.getSecond());
2. 使用DateTimeFormatter 对象来进行格式化
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH小时mm分钟ss秒");String format = dateTimeFormatter.format(ldt);System.out.println("格式化的日期="+format);
3. Instant时间戳
// 通过静态方法 now()获取代表当前时间戳的对象Instant now = Instant.now();System.out.println(now);// 通过我们的from方法可以把Instant转成DateDate date = Date.from(now);// 通过date的toInstant()可以把date转成Instant对象Instant instant = date.toInstant();
4. 第三代日期类更多方法
localDateTime类
MonthDay类:检查重复事件
是否是闰年
使用plus方法测试增加时间的某个部分
使用minus方法测试查看一年前和一年后的日期