• Java中时间类Date和Calendar的基本知识


    Date中常用的方法

    • int getYear() (返回现在到1900年所经历的年份)
    • int getMonth() (返回值是0-11)
    • int getDate() (返回的是月份中的某一天,返回值在1-31之间)
    • int getDay() (返回某周的第几天, 注: 周末为第一天, 返回值为0-6)
    • int getHours() (返回第几个小时)
    • int getMinutes() (返回多少分钟)
    • int getSeconds() (返回秒数)
    • long getTime() (获取日期对象从1970年的1月1日00:00:00到现在的时间毫秒数)
    • void setTime(long time) (设置时间,time为设置的时间到1970年1月1日00:00:00的时间毫秒数)
    • boolean after(Date when) (测试日期在指定日期之后则返回为true,否则为false)
    • boolean before(Date when) (测试日期在指定日期之前则返回为true,否则为false)

    Calendar 

    2.1、Calendar是一个接口,实例化接口有两种方法

    1. 1 : `Calendar calendar = new GregorianCalendar();`
    2. 2 : `Calendar calendar = Calendar.getInstance();`

    2.2、Calendar中常用的方法

    • calendar.getTimeInMills() (获取calendar到1970年的时间毫秒数)
    • calendar.getTime() (将当前calendar转换成Date类型);
    • calendar.get(Calendar.Year); (获取年份,与Date中获取年不同)
    • calendar.get(Calendar.DAY_OF_WEEK)等等很多类似的方法
    • calendar.set(Calendar.Year,2012);(将年份时间设置为2012年)等等也有很多类似的方法
    • calendar.set(year,month,date)set方法也可以这样写
    • calendar.add(Calendar.Year,-1); (倒退一年时间)

    例如: 让你求没一年的2月的最后一天可以用三月第一天然后都退一天得到

    Date,Calendar和String类型的联系与相互转换

    3.1、String---->Date---->Calendar

    1. String time = "20121023";
    2. SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
    3. Date parse = simpleDateFormat.parse(time);
    4. Calendar calendar = new GregorianCalendar();
    5. calendar.setTime(parse);

    3.2、Calendar---->Date---->String

    1. Calendar calendar = Calendar.getInstance();
    2. Date date = calendar.getTime();
    3. SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
    4. String format = simpleDateFormat.format(date);

    注:
    1: SimpleDateFormat不能直接用于Calendar,它主要是用于String和Date类型的相互转换.
    2: System.current.TimeMills() (从目前到1970年的时间毫秒数)
    3: 年:yyyy, 月:MM, 日: dd, 时:HH, 分: mm, 秒: ss
    4: 中国在东八区,所以会在时间上加上8个小时.
     

  • 相关阅读:
    记一次用dataframe进行数据清理
    vue3 Component API
    正则表达式完整入门教程,含在线练习
    科大讯飞交卷,实测星火大模型
    Matlab 对连续时间信号的运算
    ThreadPoolExecutor源码分析
    用大模型实现PPT可视化几种思路
    【突然想多了解一点】可以用 Task.Run() 将同步方法包装为异步方法吗?
    关于ASPICE 4.0评估师资质更新的说明-亚远景科技
    MATLAB中ss2tf函数用法
  • 原文地址:https://blog.csdn.net/m0_50370837/article/details/126679085