Java-Ch 9: 常用类(日期时间API,东西多用的时候再查)

目录

目录

1 java.util.Date类

                           |---java.sql.Date类

1.1 基础知识&例题(String和Date的转换)

1.1.1 格式化:日期 ---> 字符串  &  解析:格式化的逆过程,字符串 ---> 日期

1.2 IDEA debug

1.3 Calendar类

1.4 三种local方法

1.5 Instant 

1.6 DateTimeFormatter 类似于 SimpleDateFormat

1.6.1 格式化



1 java.util.Date类

                           |---java.sql.Date类

1.1 基础知识&例题(String和Date的转换)

package com.lee.java;

import org.junit.Test;

import java.util.Date;

/**
 * @author Lee
 * @create 2021-08-25 10:15
 */
public class DateTimeTest {
        /*
    java.util.Date类
           |---java.sql.Date类

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

    3. java.sql.Date对应着数据库中的日期类型的变量
        >如何实例化
        >sql转util 多态
        >如何将java.util.Date对象转换为java.sql.Date对象
     */
    @Test
    public void test2(){
        //构造器一:Date():创建一个对应当前时间的Date对象
        Date date1 = new Date();
        System.out.println(date1.toString());//Wed Aug 25 17:14:35 CST 2021
        System.out.println(date1.getTime());//long 毫秒数 1629858124065

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

        //创建java.sql.Date对象
        java.sql.Date date3 = new java.sql.Date(1629858124065L);
        System.out.println(date3);//2021-08-25

        //如何将java.util.Date对象转换为java.sql.Date对象
        //父类转子类
        //1.
        Date date4 = new java.sql.Date(1629858124065L);//右子类,左父类,多态上去,强转下来
        java.sql.Date date5 = (java.sql.Date) date4;

        //2.
        Date date6 = new Date();
        java.sql.Date date7 = new java.sql.Date(date6.getTime());


    }

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

1.1.1 *格式化:日期 ---> 字符串  &  解析:格式化的逆过程,字符串 ---> 日期

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

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

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

    2.SimpleDateFormat的实例化

     */

    @Test
    public void testSimpleDateFormat(){
        //实例化
        SimpleDateFormat sdf = new SimpleDateFormat();

        //格式化:日期 --->字符串
        Date date = new Date();//util下
        System.out.println(date);//Thu Aug 26 10:59:25 CST 2021

        String format = sdf.format(date);
        System.out.println(format);//21-8-26 上午11:00

        //解析:格式化的逆过程,字符串 ---> 日期
        String str = "19-08-09 上午11:44";
        try {
            Date date1 = sdf.parse(str);//无法识别"2019-08-09"
            System.out.println(date1);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        //*************按照指定的方式格式化和解析:调用带参的构造器*****************
//        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyy.MMMMM.dd GGG hh:mm aaa");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");//2021-08-26 11:08:35
        String format1 = sdf1.format(date);
        System.out.println(format1);//02021.八月.26 公元 11:07 上午
        //解析
        Date date2 = null;
        try {
            date2 = sdf1.parse("2020-02-09 11:12:23");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println(date2);//Sun Feb 09 11:12:23 CST 2020

    }

 

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

    练习二:"三天打渔两天晒网"   1990-01-01  xxxx-xx-xx 打渔?晒网?

    举例:2020-09-08 ? 总天数

    总天数 % 5 == 1,2,3 : 打渔
    总天数 % 5 == 4,0 : 晒网

    总天数的计算?
    方式一:( date2.getTime() - date1.getTime()) / (1000 * 60 * 60 * 24) + 1
    方式二:1990-01-01  --> 2019-12-31  +  2020-01-01 -->2020-09-08
     */


    
    @Test
    public void test1() {
        //创建格式
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        //对日期按照特定格式进行解析
        try {
            Date date = sdf1.parse("2020-09-08");
            //getTime()获得毫秒数
            //根据毫秒数创建指定对象
            java.sql.Date date1 = new java.sql.Date(date.getTime());
            System.out.println(date1);
        } catch (ParseException e) {
            e.printStackTrace();
        }

    @Test
    public void test2() throws ParseException {
        Date date1 = new Date();//now

        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        String date2 = "1990-01-01";
        Date date3 = sdf1.parse(date2);
//        System.out.println(date3.getTime());
        Date date4 = new Date();
//        System.out.println(date1.getTime());

        long day = (date4.getTime() - date3.getTime()) / (1000 * 60 * 60 *24) + 1;
        if (day % 5 != 4 && day % 5 != 0) {
            System.out.println("晒网");
        } else {
            System.out.println("打鱼");
        }
    }

1.2 IDEA debug

package com.lee.java;

import org.junit.Test;

/**
 * @author Lee
 * @create 2021-08-25 20:29
 */
public class IDEADebug {
    @Test
    public void test(){
        String str = null;
        StringBuffer sb = new StringBuffer();
        sb.append(str);

        System.out.println(sb.length());//4
        System.out.println(sb);//"null" (千万别答null 这是指空指针)

        StringBuffer sb1 = new StringBuffer(str);//NullPointerException
        System.out.println(sb1);
    }
}

1.3 Calendar类

    /*
    Calendar日历类(抽象类)的使用
     */
    
    @Test
    public void test3(){
        //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));//238

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

        //add()
        calendar.add(Calendar.DAY_OF_MONTH,3);
        System.out.println(calendar.get(Calendar.DAY_OF_MONTH));//25

        //getTime():日历类——>Date
        Date date = calendar.getTime();
        System.out.println(date);//Wed Aug 25 17:07:29 CST 2021

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

    }

1.4 三种local方法

/*
LocalDate、LocalTime、LocalDateTime 的使用
说明:
    1.LocalDateTime相较于LocalDate、LocalTime,使用频率要高
    2.类似于Calendar
 */
package com.lee.java;

import org.junit.Test;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;

/**
 * @author Lee
 * @create 2021-08-26 17:32
 */
public class JDK8DateTimeTest {
    @Test
    public void testDate(){
        Date date1 = new Date(2020 - 1900,9,8);
        System.out.println(date1);//Fri Oct 08 00:00:00 CST 3920
    }

    /*
    LocalDate、LocalTime、LocalDateTime 的使用
    说明:
        1.LocalDateTime相较于LocalDate、LocalTime,使用频率要高
        2.类似于Calendar
     */
    @Test
    public void test1(){
        //当前时间的实例化 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(2020, 10, 6, 13, 23, 42);
        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());//8
        System.out.println(localDateTime.getMinute());//10

        //设置 体现不可变性 localDate保留不受改变
        //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);//8
        System.out.println(localDateTime3);//11

        LocalDateTime localDateTime4 = localDateTime.minusDays(6);
        System.out.println(localDateTime);
        System.out.println(localDateTime4);
    }
}

1.5 Instant 

    /*
Instant的使用
类似于 java.util.Date类

 */
    @Test
    public void test2(){
        //now():获取本初子午线对应的标准时间
        Instant instant = Instant.now();
        System.out.println(instant);//本初子午线时间 2021-08-27T09:15:32.204Z

        //添加时间的偏移量
        OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));
        System.out.println(offsetDateTime);//2021-08-27T17:17:52.265+08:00

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

        //ofEpochMilli():通过给定的毫秒数,获取Instant实例  -->Date(long millis)
        Instant instant1 = Instant.ofEpochMilli(1630056064887L);
        System.out.println(instant1);//2021-08-27T09:21:04.887Z
    }

1.6 DateTimeFormatter 类似于 SimpleDateFormat

1.6.1 格式化

      /*
    DateTimeFormatter:格式化或解析日期、时间
    类似于SimpleDateFormat

     */

    @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);//2021-08-27T17:28:24.657
        System.out.println(str1);//2021-08-27T17:28:24.657

        //解析:字符串 -->日期
        TemporalAccessor parse = formatter.parse("2021-08-27T17:28:24.657");
        System.out.println(parse);

        //        方式二:
//        本地化相关的格式。如:ofLocalizedDateTime()
//        FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT :适用于LocalDateTime 只是格式不同

        DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);

        //格式化
        String str2 = formatter1.format(localDateTime);
        System.out.println(str2);//LONG: 2021年8月27日 下午05时33分46秒 SHORT: 21-8-27 下午5:34

        //      本地化相关的格式。如:ofLocalizedDate()
//      FormatStyle.FULL / FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT : 适用于LocalDate
        DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
        String str3 = formatter2.format(LocalDate.now());
        System.out.println(str3);//2021年8月27日 星期五

        //       重点: 方式三:自定义的格式。如: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);//2021-08-27 05:41:17

        //解析
        TemporalAccessor accessor = formatter3.parse("2021-08-27 05:41:17");
        System.out.println(accessor);
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值