【Java日期类Date、LocalDate、LocalTime、 LocalDateTime及转换】

2023-10-07 22:58

本文主要是介绍【Java日期类Date、LocalDate、LocalTime、 LocalDateTime及转换】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录

  • 日期类 Date
    • 世界标准时间 (GMT=UTC)
      • 获取日期对象及获取时间毫秒数的两种方法:
    • Date对象获取所有日期数据
      • Date对象获取当前日期
      • 时间补零占位方法抽取获取时间日期
    • SimpleDateFormat实现日期格式化与时间字符串解析
    • 日期比较与标准时间转换
      • 日期比较
      • 标准时间转换
    • 时区转换与构造方法将时间毫秒数转为日期对象
      • 时区转换
      • 时间毫秒数转为日期对象
    • 日期工具类封装
      • 日期对象格式化字符串
      • 字符串解析时间
  • 日期类 LocalDate
    • 获取当前日期
    • 根据参数设置日期
    • 使用get方法获取日期
    • 使用with方法替换当前日期
    • 使用minus方法将当前日期推前
    • 使用plus方法将当前日期推后
    • 日期比较
    • Date转换LocalDate
  • 日期类 LocalTime
    • 获取当前时间
    • 根据参数设置时间
    • 使用get方法获取时间
    • 使用with方法替换当前日期
    • 使用minus方法将当前日期推前
    • 使用plus方法将当前日期推后
    • 时间比较
    • Date转换LocalTime
  • 日期类 LocalDateTime
    • 获取日期时间
    • 格式化日期时间
    • 字符串解析日期时间
    • 比较日期时间
    • 获取带有时区的时间并格式化时间
    • 获取带有时区的时间毫秒数
  • LocalDateTime与Date转换
    • Date转换 LocalDateTime
    • LocalDateTime转换Date
  • LocalDateTime工具类封装
    • LocalDateTime格式化为时间 指定的时间格式化字符串
    • 根据时间字符串模板将时间格式字符串解析为LocalDateTime
    • LocalDateTime类型的时间转为Date类型的时间
    • Date类型的时间转为LocalDateTime类型的时间

日期类 Date

世界标准时间 (GMT=UTC)

GMT:格林威治标准时间 1900-01-01 00:00:00

从19 世纪中叶起,世界上以英国皇家格林尼治天文台公布的时间为标准时间,即“格林尼治标准时间(Greenwich Mean Time)”,简称GMT

UTC : 世界协调时间 1970-01-01 00:00:00

世界标准时间(Coordinated Universal Time),又称世界统一时间、国际协调时间、协调世界时,简称UTC,由原子钟提供,非常精确。

UTC与GMT的区别

这两者几乎是同一概念。它们都是指的格林尼治标准时间,只不过UTC的称呼更为正式一点。两者的区别在于前者是一个天文上的概念,而后者是基于一个原子钟。在UTC中,每一年或两年会有一个“闰秒”,而我们一般不理 会这个“闰秒”,但是在Java中,这造成我们有时会出现60秒或61秒。

北京时间GMT与UTC存在秒差。通常所说的北京时间,表示为UTC+8,即北京时间比世界标准时间快8小时,也即时差为8小时。

获取日期对象及获取时间毫秒数的两种方法:

方式一:使用系统类System.currentTimeMillis()获取毫秒数
输出的毫秒数是从1970-01-01 00:00:00到程序运行的时候的时间毫秒数

public class DateTest {@Testpublic void test01(){// 标准时间 UTC GMT// 1900-01-01 00:00:00// 1970-01-01 00:00:00Date date = new Date();// Thu Apr 14 20:46:15 CST 2022 System.out.println(date);long millis = System.currentTimeMillis();// 1649940375497 1970-01-01 00:00:00到程序运行的时候的时间毫秒数System.out.println(millis);}}

输出时间毫秒数

Thu Apr 14 20:46:15 CST 2022
1649940375497

方式二:使用date.getTime() 返回long数据类型
输出的毫秒数是从1970-01-01 00:00:00到程序运行的时候的时间毫秒数

public class DateTest {@Testpublic void test01(){// 标准时间 UTC GMT// 1900-01-01 00:00:00// 1970-01-01 00:00:00Date date = new Date();// Thu Apr 14 20:46:15 CST 2022 System.out.println(date);long time = date.getTime();// 1649940375467 1970-01-01 00:00:00到程序运行的时候的时间毫秒数System.out.println(time);}}

输出时间毫秒数

Thu Apr 14 20:46:15 CST 2022
1649940375467

Date对象获取所有日期数据

Date对象获取当前日期

Date 对象常用API
Date date = new Date();

方法描述
date.getYear()获取当前年份,从1900年开始的在输出年份时date.getYear() + 1900
date.getMonth()获取当前月份(0-11,0代表1月) 所以获取当前月份是 date.getMonth()+1
date.getDate()获取当前日(1-31)
date.getDay()获取当前星期X(0-6,0代表星期天)
date.getTime()获取当前时间(从1970.1.1开始的毫秒数)
date.getHours()获取当前小时数(0-23)
date.getMinutes()获取当前分钟数(0-59)
date.getSeconds()获取当前秒数(0-59)
date.toLocaleString()获取当前日期( 年 月 日 下午 : : )

年份是从1900年开始的在输出年份时date.getYear() + 1900
在这里插入图片描述
月份date.getMonth()返回的是从0到11(0是一月份)所以月份date.getMonth()+1
在这里插入图片描述
日期使用date.getDate();
在这里插入图片描述
使用date.getDay()获取星期 ,0到6表示星期日到星期六
在这里插入图片描述

public class DateTest {@Testpublic void test02(){// 日期字符串StringBuilder dateText = new StringBuilder();// 获取日期对象Date date = new Date();// 年 月 日 时 分 秒 星期int year = date.getYear() + 1900;dateText.append(year + "年");int month = date.getMonth() + 1;dateText.append(month < 10 ? "0" + month + "月" : month + "月");int dayOfMonth = date.getDate();dateText.append(dayOfMonth < 10 ? "0" + month + "日" : dayOfMonth + "日");int hours = date.getHours();dateText.append(hours < 10 ? "0" + hours + "时" : " " + hours + "时");int minutes = date.getMinutes();dateText.append(minutes < 10 ? "0" + minutes + "分" : minutes + "分");int seconds = date.getSeconds();dateText.append(seconds < 10 ? "0" + seconds + "秒" : seconds + "秒");int dayOfWeek = date.getDay();String weekDay = " 星期";switch (dayOfWeek){case 1 ->weekDay += "一";case 2 ->weekDay += "二";case 3 ->weekDay += "三";case 4 ->weekDay += "四";case 5 ->weekDay += "五";case 6 ->weekDay += "六";default -> weekDay += "日";}dateText.append(weekDay);System.out.println(dateText.toString());}
}

输出当天的日期时间

20220414222748秒 星期四

时间补零占位方法抽取获取时间日期

public abstract class BaseDateUtil {/*** 时间补零占位* @param time 时间* @return     补零后的字符串*/public static String zeroCompensation(int time){if (time < 10 ){return "0" + time;}return String.valueOf(time);}
}
public class DateTest {
@Testpublic void test002(){// 日期字符串StringBuilder dateText = new StringBuilder();// 获取日期对象Date date = new Date();// 年 月 日 时 分 秒 星期int year = date.getYear() + 1900;dateText.append(year + "年");int month = date.getMonth() + 1;dateText.append(BaseDateUtil.zeroCompensation(month) + "月");int dayOfMonth = date.getDate();dateText.append(BaseDateUtil.zeroCompensation(dayOfMonth) + "日 ");int hours = date.getHours();dateText.append(BaseDateUtil.zeroCompensation(hours) + "时");int minutes = date.getMinutes();dateText.append(BaseDateUtil.zeroCompensation(minutes) + "分");int seconds = date.getSeconds();dateText.append(BaseDateUtil.zeroCompensation(seconds) + "秒 ");int dayOfWeek = date.getDay();String weekDay = " 星期";switch (dayOfWeek){case 1 ->weekDay += "一";case 2 ->weekDay += "二";case 3 ->weekDay += "三";case 4 ->weekDay += "四";case 5 ->weekDay += "五";case 6 ->weekDay += "六";default -> weekDay += "日";}dateText.append(weekDay);System.out.println(dateText);}

输出

20220415101502秒  星期五

SimpleDateFormat实现日期格式化与时间字符串解析

SimpleDateFormat里的构造方法中需要传一个年月日时分秒模板
在这里插入图片描述
时间字符串模板中字母的定义:
在这里插入图片描述
日期格式化字符串

public class DateTest {
@Testpublic void test03() {Date date = new Date();System.out.println(date);// 实例化一个时间字符串格式对象 并传入时间字符串模板SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 将日期对象根据之前的时间字符串模板格式化为时间字符串String format = dateFormat.format(date);System.out.println(format);}
} 

输出

Fri Apr 15 10:28:00 CST 2022
2022-04-15 10:28:00

时区设置

public class DateTest {
@Testpublic void test03() {Date date = new Date();System.out.println(date);// 实例化一个时间字符串格式对象 并传入时间字符串模板SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));// 将日期对象根据之前的时间字符串模板格式化为时间字符串String format = dateFormat.format(date);System.out.println(format);}
}

输出

Fri Apr 15 10:28:39 CST 2022
2022-04-15 10:28:39

字符串转换为时间
注意:字符串模板必须与字符串格式一致

public class DateTest {
@Testpublic void test03() {Date date = new Date();System.out.println(date);// 实例化一个时间字符串格式对象 并传入时间字符串模板SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));// 将日期对象根据之前的时间字符串模板格式化为时间字符串String format = dateFormat.format(date);System.out.println(format);String source = "1983-11-22 20:30:00";try {// 根据时间字符串模板将时间字符串解析为日期对象Date parse = dateFormat.parse(source);System.out.println(parse);}catch (ParseException e){throw new RuntimeException(e);}}
}

输出

Thu Apr 14 23:15:08 CST 2022
2022-04-14 23:15:08
Tue Nov 22 20:30:00 CST 1983

日期比较与标准时间转换

日期比较

时间比较方式一:

public class DateTest {
@Testpublic void test04() {// 实例化一个时间字符串格式对象 并传入时间字符串模板SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String text01 = "1983-11-22 20:30:00";String text02 = "1988-08-11 20:30:00";try {Date date01 = dateFormat.parse(text01);Date date02 = dateFormat.parse(text02);boolean isBefore = date01.getTime() - date02.getTime() < 0 ? true : false;boolean isAfter = date01.getTime() - date02.getTime() > 0 ? true : false;System.out.println(isBefore);System.out.println(isAfter);}catch (ParseException e){throw new RuntimeException(e);}}
}

输出

true
false

使用系统自带方法时间比较方式二:

public class DateTest {
@Testpublic void test05() {// 实例化一个时间字符串格式对象 并传入时间字符串模板SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String text01 = "1983-11-22 20:30:00";String text02 = "1988-08-11 20:30:00";try {Date date01 = dateFormat.parse(text01);Date date02 = dateFormat.parse(text02);System.out.println(date01.before(date02));System.out.println(date01.after(date02));}catch (ParseException e){throw new RuntimeException(e);}}
}

输出

true
false

标准时间转换

public class DateTest {
@Testpublic void test06() {Date date = new Date();System.out.println(date);String gmtString = date.toGMTString();String localeString = date.toLocaleString();System.out.println(gmtString);System.out.println(localeString);}
}

输出

Fri Apr 15 10:40:37 CST 2022
15 Apr 2022 02:40:37 GMT
2022415日 上午10:40:37

时区转换与构造方法将时间毫秒数转为日期对象

时区转换

public class DateTest {@Testpublic void test07() {// 输出当前系统默认时区// 1000  一秒钟// 1000 * 60  一分钟// 1000 * 60 * 60  一个小时// 1000 * 60 * 60 * 8 // sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=31,lastRule=null]System.out.println(TimeZone.getDefault());// 定义时间字符串格式化模板SimpleDateFormat tokyoSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 格式化的时候设置时区tokyoSdf.setTimeZone(TimeZone.getTimeZone("Asia/Tokyo"));// 获取当前时间对象Date tokyoDate = new Date();// 将当前时间对象使用定义好的时间字符串模板格式化String tokyoDateText = tokyoSdf.format(tokyoDate);System.out.println(tokyoDateText);SimpleDateFormat NewYorkSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");NewYorkSdf.setTimeZone(TimeZone.getTimeZone("American/New Your"));Date NewYorkDate = new Date();String newYorkDateText = NewYorkSdf.format(NewYorkDate);System.out.println(newYorkDateText);}}

输出

sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=31,lastRule=null]
2022-04-15 11:46:40
2022-04-15 02:46:40

时间毫秒数转为日期对象

Date()传入时间
在这里插入图片描述

public class DateTest {@Testpublic void test08() {long time = System.currentTimeMillis();time -= 1000 * 60 * 60;Date date = new Date(time);System.out.println(date);SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));String format = dateFormat.format(date);System.out.println(format);}
}

输出

Fri Apr 15 10:26:23 CST 2022
2022-04-15 10:26:23

日期工具类封装

日期对象格式化字符串

public abstract class BaseDateUtil {/*** 默认时区*/private final static String timeZone = "Asia/Shanghai";/*** 默认时间字符串模板*/private final static String pattern = "yyyy-MM-dd HH:mm:ss";/*** 将日期对象格式化为字符串* @param date      Date对象* @return          Date对象格式化后的日期字符串*/public static String format(Date date){return format(date,timeZone,pattern);}/*** 将日期对象格式化为字符串* @param date      Date对象* @param pattern   日期格式化字符串模板* @return          Date对象格式化后的日期字符串*/public static String format(Date date, String pattern){return format(date,timeZone,pattern);}/*** 将日期对象格式化为字符串* @param date      Date对象* @param timeZone  时区* @param pattern   日期格式化字符串模板* @return          Date对象格式化后的日期字符串*/public static String format(Date date, String timeZone, String pattern){SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);dateFormat.setTimeZone(TimeZone.getTimeZone(timeZone));return dateFormat.format(date);}/*** 时间补零占位* @param time 时间* @return     补零后的字符串*/public static String zeroCompensation(int time){if (time < 10 ){return "0" + time;}return String.valueOf(time);}
}

测试

public class BaseDateUtilTest {@Testpublic void format(){System.out.println(BaseDateUtil.format(new Date(),"Asia/Shanghai","yyyy-MM-dd HH:mm:ss"));System.out.println(BaseDateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));System.out.println(BaseDateUtil.format(new Date()));}
}

输出

2022-04-16 15:55:07
2022-04-16 15:55:08
2022-04-16 15:55:08

字符串解析时间

public abstract class BaseDateUtil {/*** 默认时区*/private final static String timeZone = "Asia/Shanghai";/*** 默认时间字符串模板*/private final static String pattern = "yyyy-MM-dd HH:mm:ss";/*** 将日期字符串解析为日期对象* @param text      日期字符串* @param timeZone  时区* @param pattern   日期格式化字符串模板* @return          日期字符串解析后的日期对象* @throws ParseException*/public static Date parse(String text, String timeZone, String pattern) throws ParseException {SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);dateFormat.setTimeZone(TimeZone.getTimeZone(timeZone));return dateFormat.parse(text);}/*** 将日期字符串解析为日期对象* @param text      日期字符串* @param pattern   日期格式化字符串模板* @return          日期字符串解析后的日期对象* @throws ParseException*/public static Date parse(String text, String pattern) throws ParseException {return parse(text, timeZone, pattern);}/*** 将日期字符串解析为日期对象* @param text      日期字符串* @return          日期字符串解析后的日期对象* @throws ParseException*/public static Date parse(String text) throws ParseException {return parse(text, timeZone, pattern);}/*** 时间补零占位* @param time 时间* @return     补零后的字符串*/public static String zeroCompensation(int time){if (time < 10 ){return "0" + time;}return String.valueOf(time);}
}

测试

public class BaseDateUtilTest {@Testpublic void parse() throws ParseException {System.out.println(BaseDateUtil.parse("1983-11-22 20:30:00","Asia/Shanghai","yyyy-MM-dd HH:mm:ss"));System.out.println(BaseDateUtil.parse("1983-11-22 20:30:00","yyyy-MM-dd HH:mm:ss"));System.out.println(BaseDateUtil.parse("1983-11-22 20:30:00"));}
}

输出

Tue Nov 22 20:30:00 CST 1983
Tue Nov 22 20:30:00 CST 1983
Tue Nov 22 20:30:00 CST 1983

日期类 LocalDate

获取当前日期

使用java.time包下的LocalDate
在这里插入图片描述
使用LocalDate.now()方法获取默认时区的当前时间
在这里插入图片描述

public class LocalDateTest {@Testpublic void test(){// 获取当前日期LocalDate now = LocalDate.now();System.out.println(now);}
}

输出

2022-04-16

根据参数设置日期

使用LocalDate.of()方法传入参数在这里插入图片描述

public class LocalDateTest {
@Testpublic void test02(){// 获取当前日期LocalDate localDate = LocalDate.of(1983,11,22);System.out.println(localDate);}}

输出

1983-11-22

使用get方法获取日期

方法描述
now.getDayOfYear()获取当前日期所在年的第几天
now.getDayOfMonth()获取当前日期所在月的第几天
now.getDayOfWeek()获取当前日期所在周的星期
now.getMonthValue()获取当前日期所在月份的数值
now.getMonth()获取当前日期月份的英文单词
now.lengthOfMonth()获取当前日期所在月份有多少天
now.lengthOfYear()获取当前日期所在年份有多少天
now.isLeapYear()获取当前日期所在年是否是闰年
public class LocalDateTest {@Testpublic void test03(){// 获取当前日期是所在年或月的第几天LocalDate now = LocalDate.now();System.out.println(now.getDayOfYear());System.out.println(now.getDayOfMonth());System.out.println(now.getDayOfWeek());// 获取当前日期所在月份的数值System.out.println(now.getMonth());System.out.println(now.getMonthValue());// 获取当前日期所在月份有多少天System.out.println(now.lengthOfMonth());// 获取当前日期所在年份有多少天System.out.println(now.lengthOfYear());// 获取当前日期所在年是否是闰年System.out.println(now.isLeapYear());}}

输出

106
16
SATURDAY
APRIL
4
30
365
false

使用with方法替换当前日期

with开头的方法,是将参数替换localDate中的对应属性,重新计算得到新的日期

方法描述
now.withDayOfMonth()将参数中的“日”替换localDate中的“日”
now.withDayOfYear()将参数中的天数替换localDate中的天数(一年中的第几天)
now.withMonth()将参数中的“月”替换localDate中的“月”
now.withYear()将参数中的“年”替换localDate中的“年”
public class LocalDateTest {@Testpublic void test04(){// with开头的方法,是将参数替换localDate中的对应属性,重新计算得到新的日期LocalDate now = LocalDate.now();System.out.println(now);// 将参数中的“日”替换localDate中的“日”System.out.println(now.withDayOfMonth(7));// 将参数中的天数替换localDate中的天数(一年中的第几天)System.out.println(now.withDayOfYear(45));// 将参数中的“月”替换localDate中的“月”System.out.println(now.withMonth(11));// 将参数中的“年”替换localDate中的“年”System.out.println(now.withYear(1983));System.out.println(now.withYear(1983).withMonth(11).withDayOfMonth(22));}
}

输出

2022-04-16
2022-04-07
2022-02-14
2022-11-16
1983-04-16
1983-11-22

使用minus方法将当前日期推前

方法描述
now.minusDays()将当前日期减一天
now.minusWeeks()将当前日期减一周
now.minusMonths()将当前日期减一月
now.minusYears()将当前日期减一年
public class LocalDateTest {
@Testpublic void test05(){LocalDate now = LocalDate.now();System.out.println(now);// 将当前日期减一天System.out.println(now.minusDays(1));// 将当前日期减一周System.out.println(now.minusWeeks(1));// 将当前日期减一月System.out.println(now.minusMonths(1));// 将当前日期减一年System.out.println(now.minusYears(1));System.out.println(now.minusYears(1).minusMonths(1).minusDays(1));}
}

输出

2022-04-16
2022-04-15
2022-04-09
2022-03-16
2021-04-16
2021-03-15

使用plus方法将当前日期推后

方法描述
now.plusDays()将当前日期加一天
now.plusWeeks()将当前日期加一周
now.plusMonths()将当前日期加一月
now.plusYears()将当前日期加一年
public class LocalDateTest {
@Testpublic void test06(){LocalDate now = LocalDate.now();System.out.println(now);// 将当前日期加一天System.out.println(now.plusDays(1));// 将当前日期加一周System.out.println(now.plusWeeks(1));// 将当前日期加一月System.out.println(now.plusMonths(1));// 将当前日期加一年System.out.println(now.plusYears(1));}
}```
输出
```java
2022-04-16
2022-04-17
2022-04-23
2022-05-16
2023-04-16

日期比较

方法描述
date01.isBefore()比较日期之前
date02.isAfter()比较日期之后
public class LocalDateTest {
@Testpublic void test07(){LocalDate date01 = LocalDate.of(1983,11,22);LocalDate date02 = LocalDate.of(1988,8,11);System.out.println(date01.isBefore(date02));System.out.println(date02.isAfter(date01));}
}

输出

true
true

Date转换LocalDate

public class LocalDateTest {
@Testpublic void test08(){Date date = new Date();System.out.println(date);OffsetDateTime offsetDateTime = date.toInstant().atOffset(ZoneOffset.of("+8"));LocalDate localDate = offsetDateTime.toLocalDate();System.out.println(localDate);}
}

输出

Sun Apr 17 09:39:28 CST 2022
2022-04-17

日期类 LocalTime

获取当前时间

public class LocalTimeTest {@Testpublic void test01(){// 获取当前时间LocalTime now = LocalTime.now();System.out.println(now);}
}

输出

22:34:16.606020490

根据参数设置时间

public class LocalTimeTest {
@Testpublic void test02(){// 根据参数设置时间,参数分别是时,分,秒LocalTime localTime = LocalTime.of(10,11,22);System.out.println(localTime);}}

输出

10:11:22

使用get方法获取时间

方法描述
now.getHour()获取当前小时
now.getMinute()获取当前分钟
now.getSecond()获取当前秒钟
now.getNano()获取当前毫秒数
public class LocalTimeTest {
@Testpublic void test03(){// 获取当前时,分,秒LocalTime now = LocalTime.now();System.out.println(now.getHour());System.out.println(now.getMinute());System.out.println(now.getSecond());System.out.println(now.getNano());}}

输出

22
59
28
45087385

使用with方法替换当前日期

with开头的方法,是将参数替换localTime中的对应属性,重新计算得到新的时间

方法描述
now.withHour()将参数中的“时”替换LocalTime中的“时”
now.withMinute()将参数中的“分”替换LocalTime中的“分”
now.withSecond()将参数中的“秒”替换LocalTime中的“秒”
now.withNano()将参数中的“毫秒”替换LocalTime中的“毫秒”
public class LocalTimeTest {
@Testpublic void test04(){// with开头的方法,是将参数替换LocalTime中的对应属性,重新计算得到新的时间LocalTime now = LocalTime.now();System.out.println(now);// 将参数中的“时”替换LocalTime中的“时”System.out.println(now.withHour(7));// 将参数中的“分”替换LocalTime中的“分”System.out.println(now.withMinute(1));// 将参数中的“秒”替换LocalTime中的“秒”System.out.println(now.withSecond(1));// 将参数中的“毫秒”替换LocalTime中的“毫秒”System.out.println(now.withNano(1)); }
}

输出

22:57:20.135402090
07:57:20.135402090
22:01:20.135402090
22:57:01.135402090
22:57:20.000000001

使用minus方法将当前日期推前

方法描述
now.minusHours()将当前时间减一小时
now.withMinute()将当前时间减掉,重新得到新的分钟
now.minusSeconds()将当前时间减一秒钟
now.minusNanos()将当前时间减一毫秒钟
public class LocalTimeTest {@Testpublic void test05(){LocalTime now = LocalTime.now();System.out.println(now);// 将当前时间减一小时System.out.println(now.minusHours(1));// 将当前时间减掉,重新得到新的分钟System.out.println(now.withMinute(1));// 将当前时间减一秒钟System.out.println(now.minusSeconds(1));// 将当前时间减一毫秒钟System.out.println(now.minusNanos(1));}
}

输出

22:40:41.641537152
21:40:41.641537152
22:01:41.641537152
22:40:40.641537152
22:40:40.641537151

使用plus方法将当前日期推后

方法描述
now.plusHours()将当前时间加一小时
now.plusMinutes()将当前时间加一分钟
now.plusSeconds()将当前时间加一秒钟
now.plusNanos()将当前时间加一毫秒钟
public class LocalTimeTest {
@Testpublic void test06(){LocalTime now = LocalTime.now();System.out.println(now);// 将当前时间加一小时System.out.println(now.plusHours(1));// 将当前时间加一分钟System.out.println(now.plusMinutes(1));// 将当前时间加一秒钟System.out.println(now.plusSeconds(1));// 将当前时间加一毫秒钟System.out.println(now.plusNanos(1));}
}```
输出
```java
22:53:25.377187110
23:53:25.377187110
22:54:25.377187110
22:53:26.377187110
22:53:25.377187111

时间比较

方法描述
time01.isBefore()比较时间之前
time02.isAfter()比较时间之后
public class  LocalTimeTest {
@Testpublic void test07(){LocalTime time01 = LocalTime.of(8,8,8);LocalTime time02 = LocalTime.of(6,6,6);System.out.println(time01.isBefore(time02));System.out.println(time02.isAfter(time01));}
}

输出

false
false

Date转换LocalTime

public class  LocalTimeTest {@Testpublic void test08(){Date date = new Date();System.out.println(date);OffsetDateTime offsetDateTime = date.toInstant().atOffset(ZoneOffset.of("+8"));LocalTime localTime = offsetDateTime.toLocalTime ();System.out.println(localTime);}
}

输出

Sun Apr 17 09:50:53 CST 2022
09:50:53.437

日期类 LocalDateTime

获取日期时间

public class LocalDateTimeTest {@Testpublic void test01(){LocalDateTime now = LocalDateTime.now();System.out.println(now);}}

输出

2022-04-16T23:09:15.341262720

格式化日期时间

public class LocalDateTimeTest {@Testpublic void test02(){LocalDateTime now = LocalDateTime.now();System.out.println(now);DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");String format = formatter.format(now);System.out.println(format);}
}

输出

2022-04-16T23:10:49.533594172
2022-04-16 23:10:49

字符串解析日期时间

public class LocalDateTimeTest {
@Testpublic void test03(){// 定义时间字符串String text = "1983-11-22 20:30:30";// 将时间字符串根据模板解析为LocalDateTimeLocalDateTime parse = LocalDateTime.parse(text, formatter);System.out.println(parse);}
}

输出

1983-11-22T20:30:30

比较日期时间

public class LocalDateTimeTest {
@Testpublic void test04(){// 定义时间字符串String text = "1983-11-22 20:30:30";// 将时间字符串根据模板解析为LocalDateTimeLocalDateTime parse = LocalDateTime.parse(text, formatter);System.out.println(parse);// 获取当前时间LocalDateTime now = LocalDateTime.now();// 判断某时刻是否在某时刻之前System.out.println(parse.isBefore(now));System.out.println(parse.isAfter(now));// 判断某时刻与某时刻是否是同一时刻System.out.println(parse.isEqual(now));}
}

输出

1983-11-22T20:30:30
true
false
false

获取带有时区的时间并格式化时间

public class LocalDateTimeTest {
@Testpublic void test05(){// 获取当前时间LocalDateTime bj = LocalDateTime.now();// 获取带有时区的时间LocalDateTime tokyo = LocalDateTime.now(ZoneId.of("+9"));System.out.println("北京时间 >>> " + bj);System.out.println("日本东京时间 >>> " + tokyo);System.out.println(bj.format(formatter));System.out.println(formatter.format(tokyo));}
}

输出

北京时间 >>> 2022-04-17T08:46:25.072974735
日本东京时间 >>> 2022-04-17T09:46:25.073142716
2022-04-17 08:46:25
2022-04-17 09:46:25

获取带有时区的时间毫秒数

public class LocalDateTimeTest {@Testpublic void test06(){long second = LocalDateTime.now(ZoneOffset.of("+9")).toEpochSecond(ZoneOffset.of("+8"));System.out.println(second);long milliSecond = LocalDateTime.now(ZoneOffset.of("+9")).toInstant(ZoneOffset.of("+8")).toEpochMilli();System.out.println(milliSecond);System.out.println(System.currentTimeMillis());}
}

输出

1650160803
1650160803540
1650157203540

LocalDateTime与Date转换

Date转换 LocalDateTime

public class LocalDateTimeTest {
@Testpublic void test07(){Date date = new Date();System.out.println(date);OffsetDateTime offsetDateTime = date.toInstant().atOffset(ZoneOffset.of("+8"));LocalDateTime localDateTime = offsetDateTime.toLocalDateTime();System.out.println(localDateTime);}
}

输出

Sun Apr 17 11:04:22 CST 2022
2022-04-17T11:04:22.528

LocalDateTime转换Date

public class LocalDateTimeTest {@Testpublic void test08(){LocalDateTime now = LocalDateTime.now();System.out.println(now);Instant instant = LocalDateTime.now().toInstant(ZoneOffset.of("+8"));Date date = Date.from(instant);System.out.println(date);}
}

输出

2022-04-17T09:37:18.997785098
Sun Apr 17 09:37:18 CST 2022

LocalDateTime工具类封装

LocalDateTime格式化为时间 指定的时间格式化字符串

public class BaseLocalDateTimeUtil {/*** 时间格式化模板字符串*/private final static String formatter = "yyyy-MM-dd HH:mm:ss";/*** 将LocalDateTime格式化为时间 指定的时间格式化字符串* @param dateTime   欲被格式化的时间* @return           根据时间格式字符串模板个还是花的时间字符串*/public static String format(LocalDateTime dateTime){return DateTimeFormatter.ofPattern(formatter).format(dateTime);}/*** 将LocalDateTime格式化为时间 指定的时间格式化字符串* @param dateTime   欲被格式化的时间* @param formatter  时间字符串模板* @return           根据时间格式字符串模板个还是花的时间字符串*/public static String format(LocalDateTime dateTime,String formatter){return DateTimeFormatter.ofPattern(formatter).format(dateTime);}
}

测试

public class BaseLocalDateTimeUtilTest {@Testpublic void format(){LocalDateTime dateTime = LocalDateTime.now();System.out.println(BaseLocalDateTimeUtil.format(dateTime));System.out.println(BaseLocalDateTimeUtil.format(dateTime,"yyyy年MM月dd日 HH时mm分ss秒"));}
}

输出

2022-04-17 10:41:17
20220417104117

根据时间字符串模板将时间格式字符串解析为LocalDateTime

public class BaseLocalDateTimeUtil {/*** 时间格式化模板字符串*/private final static String formatter = "yyyy-MM-dd HH:mm:ss";/*** 根据时间字符串模板将时间格式字符串解析为LocalDateTime* @param text      时间字符串* @return*/public static LocalDateTime parse(String text){return LocalDateTime.parse(text,DateTimeFormatter.ofPattern(formatter));}/*** 根据时间字符串模板将时间格式字符串解析为LocalDateTime* @param text      时间字符串* @param formatter 时间字符串模板* @return*/public static LocalDateTime parse(String text,String formatter){return LocalDateTime.parse(text,DateTimeFormatter.ofPattern(formatter));}
}

测试

public class BaseLocalDateTimeUtilTest {@Testpublic void parse(){String text01 = "1983-11-22 20:30:30";String text02 = "1983年11月22日 20时30分30秒";System.out.println(BaseLocalDateTimeUtil.parse(text01));System.out.println(BaseLocalDateTimeUtil.parse(text02,"yyyy年MM月dd日 HH时mm分ss秒"));}
}

输出

1983-11-22T20:30:30
1983-11-22T20:30:30

LocalDateTime类型的时间转为Date类型的时间

public class BaseLocalDateTimeUtil {/*** 时间格式化模板字符串*/private final static String formatter = "yyyy-MM-dd HH:mm:ss";/*** 默认时区为东8区*/private static final ZoneOffset zoneOffset = ZoneOffset.of("+8");/*** LocalDateTime类型的时间转为Date类型的时间* @param dateTime       LocalDateTime* @retur Date*/public static  Date toDate(LocalDateTime dateTime){return Date.from(dateTime.toInstant(zoneOffset));}/*** LocalDateTime类型的时间转为Date类型的时间* @param dateTime       LocalDateTime* @param zoneOffset     时区* @retur Date*/public static  Date toDate(LocalDateTime dateTime, ZoneOffset zoneOffset){return Date.from(dateTime.toInstant(zoneOffset));}
}

测试

public class BaseLocalDateTimeUtilTest {
@Testpublic void toDate(){Date date01 = BaseLocalDateTimeUtil.toDate(LocalDateTime.now());Date date02 = BaseLocalDateTimeUtil.toDate(LocalDateTime.now(), ZoneOffset.of("+9"));System.out.println(date01);System.out.println(date02);}
}

输出

Sun Apr 17 11:29:09 CST 2022
Sun Apr 17 10:29:09 CST 2022

Date类型的时间转为LocalDateTime类型的时间

public class BaseLocalDateTimeUtil {/*** 时间格式化模板字符串*/private final static String formatter = "yyyy-MM-dd HH:mm:ss";/*** 默认时区为东8区*/private static final ZoneOffset zoneOffset = ZoneOffset.of("+8");/*** Date类型的时间转为LocalDateTime类型的时间* @param date        Date* @retur Date*/public static  LocalDateTime toDate(Date date){return date.toInstant().atOffset(zoneOffset).toLocalDateTime();}/*** Date类型的时间转为LocalDateTime类型的时间* @param date        Date* @param zoneOffset  时区* @retur Date*/public static  LocalDateTime toDate(Date date, ZoneOffset zoneOffset){return date.toInstant().atOffset(zoneOffset).toLocalDateTime();}
}

测试

public class BaseLocalDateTimeUtilTest {
@Testpublic void toDate01() {LocalDateTime localDateTime01 = BaseLocalDateTimeUtil.toDate01(Date.from(Instant.now()));LocalDateTime localDateTime02 = BaseLocalDateTimeUtil.toDate01(Date.from(Instant.now()),ZoneOffset.of("+9"));System.out.println(localDateTime01);System.out.println(localDateTime02);}
}

输出

2022-04-17T20:18:50.389
2022-04-17T21:18:50.391

这篇关于【Java日期类Date、LocalDate、LocalTime、 LocalDateTime及转换】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/160986

相关文章

java实现延迟/超时/定时问题

《java实现延迟/超时/定时问题》:本文主要介绍java实现延迟/超时/定时问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Java实现延迟/超时/定时java 每间隔5秒执行一次,一共执行5次然后结束scheduleAtFixedRate 和 schedu

Java Optional避免空指针异常的实现

《JavaOptional避免空指针异常的实现》空指针异常一直是困扰开发者的常见问题之一,本文主要介绍了JavaOptional避免空指针异常的实现,帮助开发者编写更健壮、可读性更高的代码,减少因... 目录一、Optional 概述二、Optional 的创建三、Optional 的常用方法四、Optio

Spring Boot项目中结合MyBatis实现MySQL的自动主从切换功能

《SpringBoot项目中结合MyBatis实现MySQL的自动主从切换功能》:本文主要介绍SpringBoot项目中结合MyBatis实现MySQL的自动主从切换功能,本文分步骤给大家介绍的... 目录原理解析1. mysql主从复制(Master-Slave Replication)2. 读写分离3.

idea maven编译报错Java heap space的解决方法

《ideamaven编译报错Javaheapspace的解决方法》这篇文章主要为大家详细介绍了ideamaven编译报错Javaheapspace的相关解决方法,文中的示例代码讲解详细,感兴趣的... 目录1.增加 Maven 编译的堆内存2. 增加 IntelliJ IDEA 的堆内存3. 优化 Mave

Java String字符串的常用使用方法

《JavaString字符串的常用使用方法》String是JDK提供的一个类,是引用类型,并不是基本的数据类型,String用于字符串操作,在之前学习c语言的时候,对于一些字符串,会初始化字符数组表... 目录一、什么是String二、如何定义一个String1. 用双引号定义2. 通过构造函数定义三、St

springboot filter实现请求响应全链路拦截

《springbootfilter实现请求响应全链路拦截》这篇文章主要为大家详细介绍了SpringBoot如何结合Filter同时拦截请求和响应,从而实现​​日志采集自动化,感兴趣的小伙伴可以跟随小... 目录一、为什么你需要这个过滤器?​​​二、核心实现:一个Filter搞定双向数据流​​​​三、完整代码

SpringBoot利用@Validated注解优雅实现参数校验

《SpringBoot利用@Validated注解优雅实现参数校验》在开发Web应用时,用户输入的合法性校验是保障系统稳定性的基础,​SpringBoot的@Validated注解提供了一种更优雅的解... 目录​一、为什么需要参数校验二、Validated 的核心用法​1. 基础校验2. php分组校验3

Python实现AVIF图片与其他图片格式间的批量转换

《Python实现AVIF图片与其他图片格式间的批量转换》这篇文章主要为大家详细介绍了如何使用Pillow库实现AVIF与其他格式的相互转换,即将AVIF转换为常见的格式,比如JPG或PNG,需要的小... 目录环境配置1.将单个 AVIF 图片转换为 JPG 和 PNG2.批量转换目录下所有 AVIF 图

Java Predicate接口定义详解

《JavaPredicate接口定义详解》Predicate是Java中的一个函数式接口,它代表一个判断逻辑,接收一个输入参数,返回一个布尔值,:本文主要介绍JavaPredicate接口的定义... 目录Java Predicate接口Java lamda表达式 Predicate<T>、BiFuncti

详解如何通过Python批量转换图片为PDF

《详解如何通过Python批量转换图片为PDF》:本文主要介绍如何基于Python+Tkinter开发的图片批量转PDF工具,可以支持批量添加图片,拖拽等操作,感兴趣的小伙伴可以参考一下... 目录1. 概述2. 功能亮点2.1 主要功能2.2 界面设计3. 使用指南3.1 运行环境3.2 使用步骤4. 核