[常用类]SimpleDateFormat的使用

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

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

    2.SimpleDateFormat的实例化
     */

    @Test
    public void testSimpleDateFormat() throws ParseException {
        //实例化SimpleDateFormat:使用默认的构造器
        SimpleDateFormat sdf = new SimpleDateFormat();
        
        //格式化:日期 ---> 字符串
        Date date = new Date();
        System.out.println(date);//Mon Apr 25 09:04:54 CST 2022

        String format = sdf.format(date);
        System.out.println(format);//2022/4/25 上午9:04

        //解析:格式化的逆过程,字符串 ---> 日期
        String str = "2022/4/25 上午9:08";
        Date date1 = sdf.parse(str);
        System.out.println(date1);

        //************按照指定的方式格式化和解析:调用带参的构造器*************************
//        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy.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);//2022-04-25 09:18:38
        //解析:要求字符串必须是符合SimpleDateFormat识别的格式(通过构造器参数体现)
        //否则就会抛异常
        Date date2 = sdf1.parse(format1);
        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);

        java.sql.Date birthDate = new java.sql.Date(date.getTime());
        System.out.println(birthDate);
    }

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

    举例: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
     */
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值