开发中常用类以及方法合集

日期类

Calendar

   public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        //获取当前年份
        System.out.println(calendar.get(Calendar.YEAR));
        //获取当年月份(注意要加1)
        System.out.println(calendar.get(Calendar.MONDAY+1));
        //获取周几(注意要减1)
        System.out.println(calendar.get(Calendar.DAY_OF_WEEK) - 1);
        //获取今天几号
        System.out.println(calendar.get(Calendar.DATE));
        //0---上午   1---下午
        System.out.println(calendar.get(Calendar.AM_PM));
        //获取当前时间 Date -> String
        Date time = calendar.getTime();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(simpleDateFormat.format(time));

        //计算年份
        calendar = new GregorianCalendar();
        Calendar calendar2 = new GregorianCalendar();
        calendar2.set(Calendar.YEAR, 2000);
        //2023年在2000以后
        System.out.println(calendar.after(calendar2));
        //增加年分
        calendar2.add(Calendar.YEAR,25);
        System.out.println(calendar.before(calendar2));
    }
2023
33
3
16
0
2023-08-16 10:13:34
true
true

LocalDateTime

 public static void main(String[] args) {
        //获取当前时间
        LocalDateTime now = LocalDateTime.now();
        System.out.println(now);
        //创建对象
        LocalDateTime localDateTime = LocalDateTime.of(2023, 9, 17, 2, 2, 2);
        System.out.println(localDateTime);
        //加上60秒
        System.out.println(now.plusSeconds(60));
        //减去一年
        System.out.println(now.minusYears(2));
        //修改月份为12月
        System.out.println(now.withMonth(12));
        //判断时间再之前还是之后
        System.out.println(now.isAfter(localDateTime));
        System.out.println(now.isBefore(localDateTime));
    }
2023-08-17T14:14:44.747
2023-09-17T02:02:02
2023-08-17T14:15:44.747
2021-08-17T14:14:44.747
2023-12-17T14:14:44.747
false
true

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