java日期类

114 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第6天,点击查看活动详情

今天要带大家看一下java日期类,在有时我们做项目时,需要获取当前时间,或者想指定某个时间。就需要用到java为我们提供的java日期类了。java日期类一共分为三代,让我带大家了解一下吧。

第一代日期类(Date)

第一代时间类出现在JDK1.0中,有很多方法都已过时。

首先看一下第一代时间类如何获取当前时间

        Date d1 = new Date();
        System.out.println(d1);

效果

Thu Jun 02 22:43:09 CST 2022

得出来的效果很不符合咱们中国人的习惯,于是我们还需要把格式转换一下。

        Date d1 = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss E");
        //format:将日期转换成指定格式的字符串
        String format = simpleDateFormat.format(d1);
        System.out.println(format);

效果

2022060210:52:20 星期四

创建SimpleDateFormat对象,可以指定相应的格式,使用的字母是规定好(字母不能乱写),下面是字母规定表

image.png

第二代日期类(Calendar)

Calendar是一个抽象类,并且构造器是private。所以不能直接获取,需要调用getInstance()来获取实例

        Calendar calendar =Calendar.getInstance();
        System.out.println(calendar);

效果 image-20220603225025533 这时我们会发现输出了很多内容,获取的是Calendar的字段,并把当前信息放到了字段中。

这样肯定也不好看,我们就需要转化一下格式

        Calendar calendar =Calendar.getInstance();
	System.out.println(+calendar.get(Calendar.YEAR) + "年"+ (calendar.get(Calendar.MONTH)+1) +  "月"+ calendar.get(Calendar.DAY_OF_MONTH)+"日");

效果

202263

第三代日期类(LocalDate)

获取当前时间

LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDateTime);

使用now(),返回当前日期时间的对象 效果

2022-06-03T23:46:28.051

也不是很好看,我们也需要转换一下

LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDateTime.getYear()+"年" + localDateTime.getMonthValue() + "月" + localDateTime.getDayOfMonth()+"日");

效果

202263