JAVA【常用类】【时间日期】

目录

一、jdk8之前的日期类

1. java.lang.System类

2. java.util.Date类

3. java.text.SimpleDateFormat类

4. java.util.Calendar(日历)类

 二、jdk8之后的日期类

新时间日期API 

1. LocalDate、 LocalTime、 LocalDateTime 类

2.瞬时instant

3.java.time.format.DateTimeFormatter 类


一、jdk8之前的日期类

1. java.lang.System类

System类提供的public static long currentTimeMillis()用来返回当前时间与1970年1月1日0时0分0秒之间以毫秒为单位的时间差,称为时间戳。
此方法适于计算时间差

//1.System类中的currentTimeMillis()
    @Test
    public void test1(){
        long time = System.currentTimeMillis();
        //返回当前时间与1970年1月1日0时0分0秒之间以毫秒为单位的时间差。
        //称为时间戳
        System.out.println(time);
    }

 

2. java.util.Date类

表示特定的瞬间,精确到毫秒
构造器:
Date(): 使用无参构造器创建的对象可以获取本地当前时间。
Date(long date)
常用方法
getTime():返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数。
toString():把此 Date 对象转换为以下形式的 String: dow mon dd
hh:mm:ss zzz yyyy 其中: dow 是一周中的某一天 (Sun, Mon, Tue,Wed, Thu, Fri, Sat), zzz是时间标准。
其它很多方法都过时了

//java中的Date类有两个,一个是util下的date类,一个是SQL下的date类,
//其中util下的date类为sql下的date类的父类。    
/*java.util.Date类
           |---java.sql.Date类

    1.两个构造器的使用
        >构造器一:Date():创建一个对应当前时间的Date对象
        >构造器二:创建指定毫秒数的Date对象
    2.两个方法的使用
        >toString():显示当前的年、月、日、时、分、秒
        >getTime():获取当前Date对象对应的毫秒数。(时间戳)

    3. java.sql.Date对应着数据库中的日期类型的变量
        >如何实例化
        >如何将java.util.Date对象转换为java.sql.Date对象
    @Test
    public void test2(){
        //构造器一:Date():创建一个对应当前时间的Date对象
        Date date1 = new Date();
        System.out.println(date1.toString());//Tue Jul 19 22:10:21 CST 2022

        System.out.println(date1.getTime());//1658239821057时间戳*/

        //构造器二:创建指定毫秒数的Date对象
        Date date2 = new Date(1658239821057L);
        System.out.println(date2.toString());

        //创建java.sql.Date对象,对应数据库中的日期类型变量
        java.sql.Date date3 = new java.sql.Date(35235325345L);
        System.out.println(date3);//1971-02-13

        //如何将java.util.Date对象转换为java.sql.Date对象
        //情况一:
//        Date date4 = new java.sql.Date(2343243242323L);
//        java.sql.Date date5 = (java.sql.Date) date4;
        //情况二:
        Date date6 = new Date();
        //通过时间戳来转换类型
        java.sql.Date date7 = new java.sql.Date(date6.getTime());


    }

3. java.text.SimpleDateFormat类

Date类的API不易于国际化,大部分被废弃了, java.text.SimpleDateFormat类是一个不与语言环境有关的方式来格式化和解析日期的具体类。
它允许进行格式化:日期-》文本、 解析:文本-》日期

格式化:
SimpleDateFormat() :默认的模式和语言环境创建对象
public SimpleDateFormat(String pattern): 该构造方法可以用参数pattern指定的格式创建一个对象,该对象调用:
public String format(Date date): 方法格式化时间对象date
解析:
public Date parse(String source): 从给定字符串的开始解析文本,以生成一个日期

    /*
    SimpleDateFormat的使用:SimpleDateFormat对日期Date类的格式化和解析

    1.两个操作:
    1.1 格式化:日期 --->字符串
    1.2 解析:格式化的逆过程,字符串 ---> 日期

    2.SimpleDateFormat的实例化

     */
    @Test
    public void testSimpleDateFormat() {
        //实例化SimpleDateFormat:使用默认的构造器
        SimpleDateFormat sdf = new SimpleDateFormat();

        //格式化:日期 --->字符串
        Date date = new Date();
        System.out.println(date);

        String format = sdf.format(date);
        System.out.println(format);

        //解析:格式化的逆过程,字符串 ---> 日期
        String str = "2019/12/18 上午11:43";
        Date date1 = null;
        try {
            date1 = sdf.parse(str);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        System.out.println(date1);

        //*************按照指定的方式格式化和解析:调用带参的构造器*****************
//        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyy.MMMMM.dd GGG hh:mm aaa");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        //格式化
        String format1 = sdf1.format(date);
        System.out.println(format1);//
        //解析:要求字符串必须是符合SimpleDateFormat识别的格式(通过构造器参数体现),
        //否则,抛异常
        Date date2 = null;
        try {
            date2 = sdf1.parse("2020-02-18 11:48:27");
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        System.out.println(date2);
    }

练习一:字符串"2020-09-08"转换为java.sql.Date

@Test
    public void testExer() throws ParseException {
//用字符串定义我们的要传入的字符串时间
        String birth = "2020-09-08";
//定义我们日期的格式,注意要和上面的一一对应。
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
//将我们的字符串转换为日期类型
        Date date = sdf1.parse(birth);
//        System.out.println(date);
//将我们的日期类型转换为时间戳传递给我么电脑的sql.date雷,再转换会sql类型的日期。
        java.sql.Date birthDate = new java.sql.Date(date.getTime());
        System.out.println(birthDate);
    }

4. java.util.Calendar(日历)类

Calendar是一个抽象基类,主用用于完成日期字段之间相互操作的功能。
获取Calendar实例的方法
使用Calendar.getInstance()方法
调用它的子类GregorianCalendar的构造器。


一个Calendar的实例是系统时间的抽象表示,通过get(int field)方法来取得想
要的时间信息。比如YEAR、 MONTH、 DAY_OF_WEEK、 HOUR_OF_DAY 、MINUTE、 SECOND
public void set(int field,int value)
public void add(int field,int amount)
public final Date getTime()
public final void setTime(Date date)


注意:
获取月份时: 一月是0,二月是1,以此类推, 12月是11
获取星期时: 周日是1,周二是2 , 。 。。。周六是7

 

@Test
    public void testCalendar(){
        //1.实例化
        //方式一:创建其子类(GregorianCalendar)的对象
        //方式二:调用其静态方法getInstance()
        Calendar calendar = Calendar.getInstance();
//        System.out.println(calendar.getClass());

        //2.常用方法
        //get()
        int days = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(days);
        System.out.println(calendar.get(Calendar.DAY_OF_YEAR));

        //set()
        //calendar可变性
        calendar.set(Calendar.DAY_OF_MONTH,22);
        days = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(days);

        //add()
        calendar.add(Calendar.DAY_OF_MONTH,-3);
        days = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(days);

        //getTime():日历类---> Date
        Date date = calendar.getTime();
        System.out.println(date);

        //setTime():Date ---> 日历类
        Date date1 = new Date();
        calendar.setTime(date1);
        days = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(days);

    }

 二、jdk8之后的日期类

为什么会出现新的日期类型?

可变性:像日期和时间这样的类应该是不可变的。
偏移性: Date中的年份是从1900开始的,而月份都从0开始。
格式化:格式化只对Date有用, Calendar则不行。
此外,它们也不是线程安全的;不能处理闰秒等。

如果我们想要得到2020年的9月8日,我们输入如下形式的代码,因为date是存在偏移量的。所以在使用的时候比较不方便。 

@Test
    public void testDate(){
        //偏移量
        Date date1 = new Date(2020 - 1900,9 - 1,8);
        System.out.println(date1);//Tue Sep 08 00:00:00 GMT+08:00 2020
    }

 

新时间日期API 

Java 8 吸收了 Joda-Time 的精华,以一个新的开始为 Java 创建优秀的 API。新的 java.time 中包含了所有关于本地日期(LocalDate)本地时间(LocalTime)、本地日期时间(LocalDateTime)、时区(ZonedDateTime)和持续时间(Duration)的类。历史悠久的 Date 类新增了 toInstant() 方法,用于把 Date 转换成新的表示形式。这些新增的本地化时间日期 API 大大简化了日期时间和本地化的管理。

java.time – 包含值对象的基础包
java.time.chrono – 提供对不同的日历系统的访问
java.time.format – 格式化和解析时间和日期
java.time.temporal – 包括底层框架和扩展特性
java.time.zone – 包含时区支持的类 

1. LocalDate、 LocalTime、 LocalDateTime 类

LocalDate、 LocalTime、 LocalDateTime 类是其中较重要的几个类,它们的实例是不可变的对象,分别表示使用 ISO-8601日历系统的日期、时间、日期和时间。它们提供了简单的本地日期或时间,并不包含当前的时间信息,也不包含与时区相关的信息。
>        LocalDate代表IOS格式(yyyy-MM-dd)的日期,可以存储 生日、纪念日等日期。
>        LocalTime表示一个时间,而不是日期。
>        LocalDateTime是用来表示日期和时间的, 这是一个最常用的类之一。  

方法描述
of()静态方法, 根据指定日期/时间创建对象
getDayOfMonth()/getDayOfYear()获得月份天数(1-31) /获得年份天数(1-366)
getDayOfWeek()获得星期几(返回一个 DayOfWeek 枚举值)
getMonth()获得月份, 返回一个 Month 枚举值
getMonthValue() / getYear()获得月份(1-12) /获得年份
getHour()/getMinute()/getSecond()获得当前对象对应的小时、 分钟、 秒
withDayOfMonth()/withDayOfYear()/
withMonth()/withYear()
将月份天数、 年份天数、 月份、 年份修改为指定的值并返回新的对象
plusDays(), plusWeeks(),
plusMonths(), plusYears(),plusHours()
向当前对象添加几天、 几周、 几个月、 几年、 几小时
minusMonths() / minusWeeks()/
minusDays()/minusYears()/minusHours()
从当前对象减去几月、 几周、 几天、 几年、 几小时

 

LocalDate、LocalTime、LocalDateTime 的使用
    说明:
        1.LocalDateTime相较于LocalDate、LocalTime,使用频率要高
        2.类似于Calendar
//now():获取当前的日期、时间、日期+时间
        LocalDate localDate = LocalDate.now();
        LocalTime localTime = LocalTime.now();
        LocalDateTime localDateTime = LocalDateTime.now();

        System.out.println(localDate);
        System.out.println(localTime);
        System.out.println(localDateTime);

 

//of():设置指定的年、月、日、时、分、秒。没有偏移量
        LocalDateTime localDateTime1 = LocalDateTime.of(2022, 2, 6, 13, 23, 43);
        System.out.println(localDateTime1);

//getXxx():获取相关的属性
        System.out.println(localDateTime.getDayOfMonth());
        System.out.println(localDateTime.getDayOfWeek());
        System.out.println(localDateTime.getMonth());
        System.out.println(localDateTime.getMonthValue());
        System.out.println(localDateTime.getMinute());

//体现不可变性,虽然修改了日期,
        //但是原本的日期没有发生变化,只是返回给新的变量的值发生了变化
        //withXxx():设置相关的属性
        LocalDate localDate1 = localDate.withDayOfMonth(22);
        System.out.println(localDate);
        System.out.println(localDate1);

//设置小时
 LocalDateTime localDateTime2 = localDateTime.withHour(4);
        System.out.println(localDateTime);
        System.out.println(localDateTime2);

//不可变性
//加上三个月的时间
        LocalDateTime localDateTime3 = localDateTime.plusMonths(3);
        System.out.println(localDateTime);
        System.out.println(localDateTime3);

//减去六天
LocalDateTime localDateTime4 = localDateTime.minusDays(6);
        System.out.println(localDateTime);
        System.out.println(localDateTime4);

2.瞬时instant

 Instant:时间线上的一个瞬时点。 在UNIX中,这个数从1970年开始,以秒为的单位;同样的,在Java中,也是从1970年开始,但以毫秒为单位。
java.time包通过值类型Instant提供机器视图,不提供处理人类意义上的时间单位。 Instant表示时间线上的一点,而不需要任何上下文信息,例如,时区。概念上讲, 它只是简单的表示自1970年1月1日0时0分0秒( UTC)开始的秒数。 因为java.time包是基于纳秒计算的,所以Instant的精度可以达到纳秒级。

 

方法描述
now()静态方法, 返回默认UTC时区的Instant类的对象
ofEpochMilli(long epochMilli)静态方法,返回在 1970-01-01 00:00:00基础上加上指定毫秒数之后的Instant 类的对象
atOffset(ZoneOffset offset)结合即时的偏移来创建一个 OffsetDateTime
toEpochMilli()返回1970-01-01 00:00:00到当前时间的毫秒数, 即为时间戳
@Test
    public void test2(){
        //now():获取本初子午线对应的标准时间,所以和我们当前的时间约有8个小时的时差。
        Instant instant = Instant.now();
        System.out.println(instant);//2022-07-20T02:08:03.671924Z

        //添加时间的偏移量
        OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));
        System.out.println(offsetDateTime);//2022-07-20T10:08:03.671924+08:00

        //toEpochMilli():获取自1970年1月1日0时0分0秒(UTC)开始的毫秒数  ---> Date类的getTime()
        long milli = instant.toEpochMilli();
        System.out.println(milli);

        //ofEpochMilli():通过给定的毫秒数,获取Instant实例  -->Date(long millis)
        Instant instant1 = Instant.ofEpochMilli(1658282947539L);
        System.out.println(instant1);
    }

3.java.time.format.DateTimeFormatter 类

该类提供了三种格式化方法:
预定义的标准格式。如:
①ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME
②本地化相关的格式。如: ofLocalizedDateTime(FormatStyle.LONG)
③自定义的格式。如: ofPattern(“yyyy-MM-dd hh:mm:ss”)

方法描述
ofPattern(String pattern)静 态 方 法 , 返 回 一 个 指 定 字 符 串 格 式 的
DateTimeFormatter
format(TemporalAccessor t) 格式化一个日期、 时间, 返回字符串
parse(CharSequence text)将指定格式的字符序列解析为一个日期、 时间

 

@Test
    public void test3(){
//        方式一:预定义的标准格式。如:ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME
        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        //格式化:日期-->字符串
        LocalDateTime localDateTime = LocalDateTime.now();
        String str1 = formatter.format(localDateTime);
        System.out.println(localDateTime);
        System.out.println(str1);//2022-07-20T10:17:37.329114

        //解析:字符串 -->日期
        TemporalAccessor parse = formatter.parse("2022-07-20T10:17:37.329114");
        System.out.println(parse);

//        方式二:
//        本地化相关的格式。如:ofLocalizedDateTime()
//        FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT :适用于LocalDateTime
        DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);
        //格式化
        String str2 = localDateTime.format(formatter1);
        System.out.println(str2);//2019年2月18日 下午03时47分16秒


//      本地化相关的格式。如:ofLocalizedDate()
//      FormatStyle.FULL / FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT : 适用于LocalDate
        DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
        //格式化
        String str3 = formatter2.format(LocalDate.now());
        System.out.println(str3);//2019-2-18


//       重点: 方式三:自定义的格式。如:ofPattern(“yyyy-MM-dd hh:mm:ss”)
        DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        //格式化
        String str4 = formatter3.format(LocalDateTime.now());
        System.out.println(str4);//2019-02-18 03:52:09

        //解析
        TemporalAccessor accessor = formatter3.parse("2022-02-03 03:52:09");
        System.out.println(accessor);

    }

 

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

桜キャンドル淵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值