首页 > 其他 > 详细

SimpleDateFormat类

时间:2021-06-09 09:45:56      阅读:14      评论:0      收藏:0      [点我收藏+]

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

  1. 两个操作:
  • 格式化:日期 ---> 字符串
  • 解析:格式化的逆过程,字符串 ---> 日期
  1. SimpleDateFormat的实例化
    @Test
    public void testSimpleDateFormat() throws ParseException {
        //实例化SimpleDateFormat:使用默认的构造器
        SimpleDateFormat sdf = new SimpleDateFormat();

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

        //解析:格式化的逆过程,字符串 ---> 日期
        String str = "21-6-8 下午10:51";
        Date date1 = sdf.parse(str);
        System.out.println(date1);

        //按照指定的方式进行格式化和解析:调用带参的构造器
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        //格式化
        String format1 = sdf1.format(date);
        System.out.println(format1);
        //解析:要求字符串必须是符合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 sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf.parse(birth);
        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

    @Test
    public void testExer2() throws ParseException {
        String date1 = "1990-01-01";
        String date2 = "2020-09-08";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date d1 = sdf.parse(date1);
        Date d2 = sdf.parse(date2);
        long time = (d2.getTime() - d1.getTime()) / (1000*60*60*24) + 1;
        long a = time%5;
        if (a < 0) {
            System.out.println("输入的时间不对!");
        }
        if (a > 0 && a < 4 ) {
            System.out.println("今天在打鱼!");
        }
        if (a == 0 || a == 4) {
            System.out.println("今天在晒网!");
        }
        System.out.println();
    }

SimpleDateFormat类

原文:https://www.cnblogs.com/koito/p/14865093.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!