Java日期类Date常用方法介绍

1.常用方法

1.获取当前时间、定义指定时间

    Calendar calendar = Calendar.getInstance();
    //获取当前时间
    Date time = calendar.getTime();
    System.out.println(time);
    //定义指定时间,月默认从0开始
    calendar.set(2023,4,12,12,12,12);
    System.out.println(calendar.getTime());

2.获取年月日时分秒相关功能

    Calendar calendar = Calendar.getInstance();

    //获取年
    System.out.println(calendar.get(Calendar.YEAR));
    //获取月
    System.out.println(calendar.get(Calendar.MONTH)+1);
    //获取日
    System.out.println(calendar.get(Calendar.DATE));

    //获取时
    System.out.println(calendar.get(Calendar.HOUR_OF_DAY));
    //获取分
    System.out.println(calendar.get(Calendar.MINUTE));
    //获取秒
    System.out.println(calendar.get(Calendar.SECOND));
    //获取一天第几天
    System.out.println(calendar.get(Calendar.DAY_OF_YEAR));
    //获取一个月第几天
    System.out.println(calendar.get(Calendar.DAY_OF_MONTH));
    //获取星期几
    System.out.println(calendar.get(Calendar.DAY_OF_WEEK)-1);

Java日期类Date常用方法介绍_第1张图片

3.日期计算相关

    Calendar calendar = Calendar.getInstance();

    //一天后
    calendar.add(Calendar.DATE,1);
    System.out.println(calendar.getTime());
    Calendar calendar1 = Calendar.getInstance();
    //一周后
    calendar1.add(Calendar.WEDNESDAY,1);
    System.out.println(calendar1.getTime());

    //一月后
    Calendar calendar2 = Calendar.getInstance();
    calendar2.add(Calendar.MONTH,1);
    System.out.println(calendar2.getTime());

    //一年后
    Calendar calendar3= Calendar.getInstance();
    calendar3.add(Calendar.YEAR,1);
    System.out.println(calendar3.getTime());

 Java日期类Date常用方法介绍_第2张图片

4.日期比较前后

    Calendar calendar = Calendar.getInstance();

    //一天后
    calendar.add(Calendar.DATE,1);
    Date time = calendar.getTime();
    //当前时间
    Date dateNow = new Date();
    System.out.println(dateNow.before(time));

    System.out.println(dateNow.after(time));
    System.out.println(dateNow.equals(time));

5.日期转字符串和字符串转日期

    //日期转字符串
    Date date = new Date();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String format = dateFormat.format(date);
    System.out.println(format);

    //字符串转日期
    SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    try {
        Date parse = dateFormat1.parse(format);
        System.out.println(parse);
    } catch (ParseException e) {
        e.printStackTrace();
    }

你可能感兴趣的:(java-spring,java,开发语言)