java.time.LocalDateTime详解

目录

静态方法

案例代码

案例代码

实例方法

转换类方法

获取类方法

替换类方法

判断类方法

增加类方法

减少类方法

其他方法


看到这篇文章的你还在用过期的时间java.util.Date吗,看完本章后,可以果断抛弃它了,因为java.time包下有他的替代品,而且功能比它更强大。

学习一个API,主要学习如何使用,接下来进入正题,介绍LocalDateTime的常用方法及使用。(因为String是CharSequence最常用的实现类,本文将使用“字符串”代替“字符序列”)

java.time.LocalDateTime是java.time.Temporal的实现类,用来表示包含年月日时分秒和纳秒的某个时间点,如:2022年9月30日9点08分55秒05纳秒。可以表示的时间范围是【-999999999年1月1日0时0分】到【999999999年12月31日23时59分59.99999999秒】

静态方法

1、static LocalDateTime now():获取当前时间,如:2022-09-30T09:44:35.750

2、static LocalDateTime of():该方法用于指定 年 月 日 时 分 秒 纳秒 创建一个LocalDateTime对象,该方法有7个重载的方法

static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute):指定年、月、日、时、分

static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute):指定年、月、日、时、分

static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute, int second):指定年、月、日、时、分、秒

static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute, int second):指定年、月、日、时、分、秒

static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond):指定年、月、日、时、分、秒、纳秒

static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond):指定年、月、日、时、分、秒、纳秒

static LocalDateTime of(LocalDate date, LocalTime time):通过指定的年月日(LocalDate )和时分秒(LocalTime )对象创建

3、static LocalDateTime parse():通过解析字符串生成LocalDateTime对象,该方法可以通过传入一个DateTimeFormatter指定传入字符串的格式,如2022-09-30 09:27:50

static LocalDateTime parse(CharSequence text):解析指定字符串生成LocalDateTime对象(LocalDateTime的字符串默认格式为2022-09-30T09:27:50)
【源码注释】:Obtains an instance of LocalDateTime from a text string such as 2007-12-03T10:15:30
static LocalDateTime parse(CharSequence text, DateTimeFormatter formatter):指定解析字符串的格式,通过创建DateTimeFormatter对象时指定

案例代码

public class LocalDateTimeExample {
    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

        // 通过默认格式yyyy-MM-ddTHH:mm:ss解析
        System.out.println(LocalDateTime.parse("2022-09-30T08:42:30"));

        // 指定字符串格式为yyyyMMddHHmmss
        System.out.println(LocalDateTime.parse("20220930084455", formatter));
    }

}

实例方法

转换类方法

1、LocalDate toLocalDate():转为LocalDate对象

2、LocalTime toLocalTime():转为LocalTime对象

获取类方法

1、int getDayOfYear():获取当前时间是今年的第几天

2、int getDayOfMonth():获取当前时间是这个月的第几天

3、DayOfWeek getDayOfWeek():获取当前时间是这周的星期几

DayOfWeek是一个枚举,定义了每周的星期一到星期日
public enum DayOfWeek implements TemporalAccessor, TemporalAdjuster {
    MONDAY, // 星期一
    TUESDAY, // 星期二
    WEDNESDAY, // 星期三
    THURSDAY, // 星期四
    FRIDAY, // 星期五
    SATURDAY, // 星期六
    SUNDAY; // 星期日
}

4、int getYear():获取年份

5、int getMonthValue():获取月份

6、Month getMonth():获取月份,该方法返回Month对象

7、int getHour():获取小时

8、int getMinute():获取分钟

9、int getSecond():获取秒

10、int getNano():获取纳秒

替换类方法

1、LocalDateTime withYear(int year):使用指定年替换原来的年份

2、LocalDateTime withMonth(int month):使用指定月替换原来的月份

3、LocalDateTime withHour(int hour):使用指定小时替换原来的小时

4、LocalDateTime withMinute(int minute):使用指定分钟替换原来的分钟

5、LocalDateTime withSecond(int second):使用指定秒替换原来的秒

6、LocalDateTime withNano(int nanoOfSecond):使用指定纳秒替换原来的纳秒

7、LocalDateTime withDayOfMonth(int dayOfMonth):替换原来月份的第几天

8、LocalDateTime withDayOfYear(int dayOfYear):替换原来年份的第几天

public class LocalDateTimeExample {
    public static void main(String[] args) {
        LocalDateTime localDate = LocalDateTime.now();
        
        System.out.println(localDate.withYear(5));
        System.out.println(localDate.withMonth(6));
        System.out.println(localDate.withHour(7));
        System.out.println(localDate.withMinute(8));
        System.out.println(localDate.withSecond(9));
        System.out.println(localDate.withNano(10));

        // 今天是2022年9月30号
        // 今天是本月第30天,改为第11天,即9月11号
        System.out.println(localDate.withDayOfMonth(11));
        // 今天是今年的第273天,改为第12天,即1月12号
        System.out.println(localDate.withDayOfYear(12));
    }

}

以上代码的运行结果为:注意观察年份、月份、小时、分钟秒和毫秒

0005-09-30T10:36:42.285
2022-06-30T10:36:42.285
2022-09-30T07:36:42.285
2022-09-30T10:08:42.285
2022-09-30T10:36:09.285
2022-09-30T10:36:42.000000010
2022-09-11T10:36:42.285
2022-01-12T10:36:42.285

9、LocalDateTime with(TemporalField field, long newValue):指定时间域替换,关于TemporalField,您可以先通过TemporalField的简单介绍了解一下。

例如:以下两个方法的调用是等效的。

LocalDateTime dateTime = LocalDateTime.now();

dateTime.withDayOfMonth(5);
dateTime.with(ChronoField.DAY_OF_MONTH, 5);

代码运行结果:

2022-09-05T11:17:19.474
2022-09-05T11:17:19.474

判断类方法

1、boolean isAfter(ChronoLocalDateTime<?> other):判断是否在指定时间之后

2、boolean isBefore(ChronoLocalDateTime<?> other):判断是否在指定时间之前

3、boolean isEqual(ChronoLocalDateTime<?> other):判断和指定时间是否相等

4、boolean isSupported(TemporalUnit unit):是否支持指定时间单位,源码中说明了LocalDateTime只支持以下单位

NANOS
MICROS
MILLIS
SECONDS
MINUTES
HOURS
HALF_DAYS
DAYS
WEEKS
MONTHS
YEARS
DECADES
CENTURIES
MILLENNIA
ERAS

5、boolean isSupported(TemporalField field):是否支持指定时间域,LocalDateTime只支持以下单位

NANO_OF_SECOND
NANO_OF_DAY
MICRO_OF_SECOND
MICRO_OF_DAY
MILLI_OF_SECOND
MILLI_OF_DAY
SECOND_OF_MINUTE
SECOND_OF_DAY
MINUTE_OF_HOUR
MINUTE_OF_DAY
HOUR_OF_AMPM
CLOCK_HOUR_OF_AMPM
HOUR_OF_DAY
CLOCK_HOUR_OF_DAY
AMPM_OF_DAY
DAY_OF_WEEK
ALIGNED_DAY_OF_WEEK_IN_MONTH
ALIGNED_DAY_OF_WEEK_IN_YEAR
DAY_OF_MONTH
DAY_OF_YEAR
EPOCH_DAY
ALIGNED_WEEK_OF_MONTH
ALIGNED_WEEK_OF_YEAR
MONTH_OF_YEAR
PROLEPTIC_MONTH
YEAR_OF_ERA
YEAR
ERA

增加类方法

1、LocalDateTime plusYears(long years):增加指定年数

2、LocalDateTime plusMonths(long months):增加指定月数

3、LocalDateTime plusWeeks(long weeks):增加指定周数

4、LocalDateTime plusDays(long days):增加指定天数

5、LocalDateTime plusHours(long hours):增加指定小时数

6、LocalDateTime plusMinutes(long minutes):增加指定分钟数

7、LocalDateTime plusSeconds(long seconds):增加指定秒数

8、LocalDateTime plusNanos(long nanos):增加指定纳秒数

9、LocalDateTime plus(TemporalAmount amountToAdd):增加指定的时间数量

10、LocalDateTime plus(long amountToAdd, TemporalUnit unit):增加指定数量的时间单位

public class LocalDateTimeExample {
    public static void main(String[] args) {
        LocalDateTime dateTime = LocalDateTime.now();

        System.out.println(dateTime);
        System.out.println(dateTime.plusYears(2));
        System.out.println(dateTime.plusMonths(2));
        System.out.println(dateTime.plusWeeks(2));
        System.out.println(dateTime.plusHours(2));
        System.out.println(dateTime.plusMinutes(2));
        System.out.println(dateTime.plusSeconds(2));
        System.out.println(dateTime.plusNanos(2));
        System.out.println(dateTime.plus(Period.ofDays(2)));
        System.out.println(dateTime.plus(2, ChronoUnit.DAYS));
    }

}

运行结果:

2022-09-30T14:36:10.986
2024-09-30T14:36:10.986
2022-11-30T14:36:10.986
2022-10-14T14:36:10.986
2022-09-30T16:36:10.986
2022-09-30T14:38:10.986
2022-09-30T14:36:12.986
2022-09-30T14:36:10.986000002
2022-10-02T14:36:10.986
2022-10-02T14:36:10.986

减少类方法

减少类方法plus()和plusXxxs()和增加类方法用法类似,这里就不介绍了。

其他方法

1、ValueRange range(TemporalField field):获取LocalDateTime支持的时间域的范围,如:

LocalDateTime dateTime = LocalDateTime.now();
// 一天有24小时,所以支持0~23
System.out.println(dateTime.range(ChronoField.HOUR_OF_DAY)); // 0-23

2、LocalDateTime truncatedTo(TemporalUnit unit):控制时间只显示到指定单位,TemporalUnit 请参考TemporalUnit简单介绍,最少会显示到分钟,更小的的单位不显示或显示为0,指定的单位最大为天,即最少可以显示为年月日(如:参数指定为分钟则秒不会显示,指定为小时,分钟会显示为00)

public class LocalDateTimeExample {
    public static void main(String[] args) {
        LocalDateTime dateTime = LocalDateTime.now();

        System.out.println(dateTime.truncatedTo(ChronoUnit.DAYS));
        System.out.println(dateTime.truncatedTo(ChronoUnit.HOURS));
        System.out.println(dateTime.truncatedTo(ChronoUnit.MINUTES));
        System.out.println(dateTime.truncatedTo(ChronoUnit.SECONDS));
        System.out.println(dateTime.truncatedTo(ChronoUnit.MILLIS));
    }

}

以上代码运行结果为:

2022-09-30T00:00
2022-09-30T11:00
2022-09-30T11:56
2022-09-30T11:56:48
2022-09-30T11:56:48.042

3、String format(DateTimeFormatter formatter):将时间格式化为字符串,可以通过接收的DateTimeFormatter对象指定转换的日期字符串格式

public class LocalDateTimeExample {
    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        LocalDateTime localDate = LocalDateTime.now();
        String format = localDate.format(formatter);

        System.out.println(format); // 20220930120236
    }

}

对比Date,java.util.Date通过java.text.SimpleDateFormat格式化

public class LocalDateTimeExample {
    public static void main(String[] args) {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date();
        String format = format.format(date);

        System.out.println(format);
    }
}

4、long until(Temporal endExclusive, TemporalUnit unit):计算指定时间离当前时间相差多少个指定的时间单位,如果指定时间endExclusive在当前时间之前,返回负数

public class LocalDateTimeExample {
    public static void main(String[] args) {
        LocalDateTime dateTime = LocalDateTime.now();
        LocalDateTime time = LocalDateTime.of(2022, 9, 30, 14, 5, 50);
        long hours = dateTime.until(time, ChronoUnit.HOURS);
        long minutes = dateTime.until(time, ChronoUnit.MINUTES);
        long seconds = dateTime.until(time, ChronoUnit.SECONDS);

        System.out.println(dateTime);
        System.out.println(time);
        System.out.println(hours);
        System.out.println(minutes);
        System.out.println(seconds);
    }

}

以上代码运行结果为:

2022-09-30T14:13:12.829
2022-09-30T14:05:50
0
-7
-442

结果解析:运行时刻的时间为14:13:12.289,指定时间为14:05:50,两者相差了7分钟,没有问题,相差了(442 = 7 * 60 + 22)秒,即7分钟22秒,也没问题。


 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
java.util包是Java中一个非常重要的包,它包含了一些在Java应用程序中经常使用的类,比如集合类、日期与时间处理类、随机数生成类、正则表达式类等。下面是java.util中一些常用类的使用方法详解。 1. 集合类 Java集合框架定义了一组接口用于表示集合,以及一些实现这些接口的类。这些类包括ArrayList,LinkedList,HashSet,TreeSet,HashMap,TreeMap等。它们提供了各种方法来添加、删除、查找和遍历集合元素。 以ArrayList为例,以下是一些常用方法: ``` // 创建ArrayList对象 ArrayList<String> list = new ArrayList<String>(); // 添加元素 list.add("apple"); list.add("banana"); list.add("orange"); // 获取元素 String first = list.get(0); String last = list.get(list.size() - 1); // 遍历元素 for (String fruit : list) { System.out.println(fruit); } // 删除元素 list.remove("apple"); ``` 2. 日期与时间处理类 Java提供了多种处理日期和时间的类,包括Date,Calendar,SimpleDateFormat等。其中,Date类表示日期和时间,Calendar类是一个抽象类,用于操作日期和时间,SimpleDateFormat类用于格式化日期和时间。 以下是一个使用SimpleDateFormat类将日期格式化为指定字符串的示例: ``` Date date = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String formattedDate = formatter.format(date); System.out.println(formattedDate); ``` 3. 随机数生成类 Java提供了Random类用于生成随机数。它包含了多个方法,可以生成不同类型的随机数,如整数、浮点数、布尔值等。 以下是一个生成1到6之间的随机整数的示例: ``` Random rand = new Random(); int num = rand.nextInt(6) + 1; System.out.println(num); ``` 4. 正则表达式类 Java提供了Pattern和Matcher类用于处理正则表达式。Pattern类表示正则表达式,Matcher类用于在给定输入字符串中匹配该正则表达式。 以下是一个使用正则表达式匹配邮政编码的示例: ``` String zipCodePattern = "\\d{5}"; Pattern pattern = Pattern.compile(zipCodePattern); String input = "12345"; Matcher matcher = pattern.matcher(input); if (matcher.matches()) { System.out.println("Valid zip code"); } else { System.out.println("Invalid zip code"); } ``` 以上是java.util包中一些常用类的使用方法详解,这些类在Java应用程序中经常用到,掌握它们的使用方法对于Java开发者来说非常重要。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值