Java日期、时间专题合集

Java日期、时间专题合集

Java中有两套日期类体系,一种是JDK8之前的,还有一种是JDK8之后的。

JDK8之前传统的日期和时间#

Date#

Date代表当前日期和时间,Date类有多个构造器和方法,但大多都已过时就不在讲述了,以下是常用为过时的构造器和方法。

构造器 说明
public Date() 创建一个Date对象,代表的是系统当前此刻日期时间
public Date(long time) 把时间毫秒值转换成Date日期对象
常见方法 说明
public long getTime() 返回从1970年1月1日 00:00:00到此刻的总毫秒数
public void setTime(long time) 设置日期对象的时间为当前时间毫秒值对应的时间
// 创建一个Date的对象:代表当前系统的时间信息
Date date = new Date();
System.out.println(date); // Tue Oct 03 16:26:16 CST 2023

// 拿到时间毫秒值
long time = date.getTime();
System.out.println(time); // 1696321576096

// 把时间毫秒值转换为日期对象:5s后的时间是多少
time += 5 * 1000;
Date afterDate = new Date(time);
System.out.println(afterDate); // Tue Oct 03 16:26:21 CST 2023

// 直接把日期对象的时通过setTime方法进行转换
time += 5 * 1000;
afterDate.setTime(time);
System.out.println(afterDate); // Tue Oct 03 16:26:26 CST 2023

SimpleDateFormat#

SimpleDateFormat代表简单日期格式化,可以用来把日期对象、时间毫秒值格式化成我们想要的格式。

常见构造器 说明
public SimpleDateFormat(String pattern) 创建简单日期格式化对象,并封装时间的格式
格式化时间的方法 说明
public final String format(Date date) 将日期格式化成日期/时间字符串
public final String format(Object time) 将时间毫秒值格式化成日期/时间字符串

时间格式的常见符号

img

// 准备日期对象和时间毫秒值
Date date = new Date();
long time = date.getTime();

// 格式化日期对象和时间毫秒值
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss EEE a");

String f1 = simpleDateFormat.format(date);
String f2 = simpleDateFormat.format(time += 5 * 1000);

// 输出格式化后的日期
System.out.println(f1); // 2023-10-03 16:45:05 星期二 下午
System.out.println(f2); // 2023-10-03 16:45:10 星期二 下午

将字符串类型时间转换为日期对象

public static void main(String[] args) throws ParseException {
    // 书写字符串类型时间
    String dateStr = "2023-10-03 20:22:10";
    // 创建简单日期格式化对象,指定的时间格式必须与被解析的时间格式一模一样,否则会报错
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    Date parse = simpleDateFormat.parse(dateStr);
    System.out.println(parse); // 2023-10-03 16:45:10 星期二 下午
}

Calendar#

方法名 说明
public static Calendar getInstance() 获取当前日历对象
public int get(int field) 获取日历中的某个信息
public final Date getTime() 获取日期对象
public long getTimeInMillis() 获取时间毫秒值
public void set(int field, int value) 修改日历的某个信息
public void add(int field, int amount) 为某个信息增加/减少指定的值
class TestCalendar {
    public static void main(String[] args) {
        // 得到系统此刻时间对应的日历对象
        Calendar now = Calendar.getInstance();
        System.out.println(now); // java.util.GregorianCalendar[time=1696324606395,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=31,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2023,MONTH=9,WEEK_OF_YEAR=40,WEEK_OF_MONTH=1,DAY_OF_MONTH=3,DAY_OF_YEAR=276,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=1,AM_PM=1,HOUR=5,HOUR_OF_DAY=17,MINUTE=16,SECOND=46,MILLISECOND=395,ZONE_OFFSET=28800000,DST_OFFSET=0]

        // get 获取日历中的某个信息
        int y = now.get(Calendar.YEAR);
        int m = now.get(Calendar.MONTH);
        int d = now.get(Calendar.DAY_OF_MONTH);
        System.out.println(y + "-" + m + "-" + d); // 2023-9-3

        // getTime 拿到日历中的日期对象
        Date date = now.getTime();
        System.out.println(date); // Tue Oct 03 17:16:46 CST 2023

        // getTimeInMillis 拿到时间毫秒值
        long timeInMillis = now.getTimeInMillis();
        System.out.println(timeInMillis); // 1696324606395

        // set 修改日历中的某个信息
        now.set(Calendar.YEAR, 2030);
        System.out.println(now); // ... YEAR=2030 ...
        
        // add 为某个信息增加或者减少
        now.add(Calendar.MONTH, -1);
        now.add(Calendar.DAY_OF_MONTH, 10);
        System.out.println(now);
    }
}

JDK8新增的日期和时间#

LocalDate、LocalTime、LocalDateTIme#

LocalDate 本地日期(年、月、日、星期)
LocalTime本地时间(时、分、秒、纳秒)
LocalDateTime本地日期、时间(年、月、日、星期、时、分、秒、纳秒)

  • 以上三个日期对象所有的方法非常相似,以下拿LocalDate举例
class TestLocalDate {
    public static void main(String[] args) {
        // 获取本地日期对象(不可变)
        // 三者都可以通过 .now 获取
        LocalDate now = LocalDate.now();
        System.out.println(now); // 2023-10-03

        // getXxx 获取日期对象中的信息
        int year = now.getYear(); // 获取年
        int month = now.getMonthValue(); // 获取月(1-12)
        int dayOfMonth = now.getDayOfMonth(); // 获取日
        int dayOfWeek = now.getDayOfWeek().getValue(); // 星期几
        System.out.println(year + " | " + month + " | " + dayOfMonth + " | " + dayOfWeek); // 2023 | 10 | 3 | 2

        // withXxx 修改某个信息
        LocalDate localDate = now.withYear(2030);
        System.out.println(now); // 2023-10-03
        System.out.println(localDate); // 2030-10-03

        // plusXxx 把某个信息加多少
        LocalDate localDate1 = now.plusYears(10);
        System.out.println(localDate1); // 2033-10-03

        // minusXxx 把某个信息减多少
        LocalDate localDate2 = now.minusDays(30);
        System.out.println(localDate2); // 2023-09-03

        // 获取指定时间的LocalTime对象
        // public static LocalTime(int hour,int minute,int second)
        LocalTime of = LocalTime.of(20, 30, 12);
        LocalTime of1 = LocalTime.of(20, 30, 12);

        // equals,isBefore,isAfter 判断两个时间对象是否相等
        System.out.println(of.equals(of1)); // true
    }
}

ZoneId、ZonedDateTime#

ZoneId:时区

ZonedDateTime:带时区的时间

class TestZoneIdAndZonedDatTime{
    public static void main(String[] args) {
        // 1. ZoneId的常见方法
        // public static ZonedId systemDefault() // 获取系统默认时区
        ZoneId zoneId = ZoneId.systemDefault();
        System.out.println(zoneId.getId()); // Asia/Shanghai
        System.out.println(zoneId); // Asia/Shanghai

        // getAvailableZoneIds() 获取Java支持的全部时区id
        System.out.println(ZoneId.getAvailableZoneIds());

        // of(String zoneId) 把某个时区id封装成ZoneId对象
        ZoneId of = ZoneId.of("America/New_York");
        System.out.println(of); // America/New_York

        // 2. ZonedDateTime 带时区的时间
        // now(ZoneId zone) 获取带某个时区的ZonedDateTIme对象
        ZonedDateTime now = ZonedDateTime.now(of);
        System.out.println(now); // 2023-10-03T09:52:07.486-04:00[America/New_York]

        // now() 获取系统默认时区的ZonedDateTime对象
        ZonedDateTime now1 = ZonedDateTime.now();
        System.out.println(now1); // 2023-10-03T21:52:07.500+08:00[Asia/Shanghai]
    }
}

Instant:时间戳 用来替代 Date

  • 通过获取Instant的对象可以拿到此刻的时间,该时由两部分组成:从1970-01-01 00:00:00 开始走到此刻的总秒数 + 不够1秒的纳秒数
方法名 说明
public static Instant now() 获取当前时间的Instant对象(标准时间)
public long getEpochSecond() 获取1970-01-01 00:00:00开始记录的秒数
public int getNano() 从时间线开始,获取从第二个开始的纳秒数
plasMillis plusSeconds plusNanos 判断系列的方法
minusMillis minusSeconds minusNanos 减少时间系列的方法
equals, isBefore, isAfter 增加时间系列的方法
  • 作用:可以用来记录代码的执行时间,或用于记录用户操作某个事件的事件点
  • 传统的Data类,只能精确到毫秒,并且是可变对象。
  • 新增的Instant类,可以精确到纳秒,并且是不可变对象,二者推荐使用Instant。
class Test_Instant{
    public static void main(String[] args) {
        // 创建Instant的对象,获取此刻的时间
        Instant now = Instant.now();
        System.out.println(now); // 2023-10-04T03:08:58.727Z

        // 获取总秒数
        long epochSecond = now.getEpochSecond();
        System.out.println(epochSecond); // 1696388938

        // 获取总纳秒
        int nano = now.getNano();
        System.out.println(nano); // 727000000
    }
}

DateTImeForMatter#

DateTimeForMatter:格式化器,用于时间的格式化、解析 用来替代 SimpleDate

  • DateTimeFormatter 方法

    方法名 说明
    public static DateTimeFormatter ofPattern(时间格式) 获取格式化器对象
    public String format(时间对象) 格式化时间
  • LocalDateTime提供的格式化、解析时间的方法

    方法名 说明
    public String format(DateTimeFormatter fomatter) 格式化时间
    public static LocalDateTime parse(CharSequence text, DateTimeFormatter formatter) 解析时间
class Test_DateTimeFormatter{
    public static void main(String[] args) {
        // 1. 创建一个日期时间格式化器对象出来
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 2. 对时间进行格式化
        LocalDateTime now = LocalDateTime.now();
        System.out.println(now); // 2023-10-03T22:28:29.983

        String format = formatter.format(now); // 正向格式化
        System.out.println(format); // 2023-10-03 22:28:29

        // 3. 格式化时间的第二种方案
        String format1 = now.format(formatter);
        System.out.println(format1); // 2023-10-03 22:28:29

        // 4. 解析时间使用LocalDateTime提供的解析方法
        String dateStr = "2020-12-10 20:28:30";
        LocalDateTime parse = LocalDateTime.parse(dateStr, formatter);
        System.out.println(parse); // 2020-12-10T20:28:30
    }
}

Period:计算日期间隔(年,月,日)

class Test_Period{
    public static void main(String[] args) {
        // 创建两个时间点
        LocalDate start = LocalDate.of(2003, 4, 1);
        LocalDate end = LocalDate.of(2023, 10, 3);

        // 创建Period对象,封装两个日期对象
        Period period = Period.between(start, end);

        // 通过period对象获取两个日期相差的信息
        System.out.println(period.getYears()); // 20
        System.out.println(period.getMonths()); // 6
        System.out.println(period.getDays()); // 2
    }
}

Duration:计算时间间隔(时,分,秒,纳秒)

class Test_Duration{
    public static void main(String[] args) {
        // 创建两个时间点
        LocalDateTime start = LocalDateTime.of(2003, 4, 1,8,30,30);
        LocalDateTime end = LocalDateTime.of(2023, 10, 3,8,30,30 );

        // 得到Duration对象
        Duration duration = Duration.between(start, end);

        // 通过period对象获取两个日期相差的信息
        System.out.println(duration.toDays()); // 7490
        System.out.println(duration.toHours()); // 179760
        System.out.println(duration.toMinutes()); // 10785600
    }
}
posted @   sroot  阅读(13)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
点击右上角即可分享
微信分享提示
主题色彩