目录

工欲善其事

实践出真知

活跃标签: linux java mysql 待分类 js springboot win10 电路 vue macOS nginx esp32 git docker windows idea maven esp8266 python Arduino

存档:

X

LocalDateTime中增加、减少、直接修改时间的方法、计算时间间隔的方法

一、LocalDateTime中增加或者减少时间的方法

1.增加或减少年份(第一种方法):调用plusYears()方法,括号中传入增加或减少的年数

  • 传入的参数为正数时,表示增加年份
  • 传入的参数为负数时,表示减少年份

代码示例:

public static void main(String[] args) {
        //先创建一个LocalDateTime对象:2020,11,11,13:14:15
        LocalDateTime localDateTime = LocalDateTime.of(2020, 11, 11, 13, 14, 15);
        //用对象调用plusYears方法(也可以调用月、日、小时等等的方法)
        //这里是增加年份的方法,传入参数1,表示年数增加1
        LocalDateTime newLocalDateTime = localDateTime.plusYears(1);
        //再格式化一下
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
        String s = newLocalDateTime.format(pattern);
        System.out.println(s);
        //输出2021年11月11日 13:14:15
    }

增加月份、天数、小时、分钟等,都是调用相应的方法:

2.增加或减少年份(第二种方法):调用minusYears()方法,括号中传入增加或减少的年数

minus与plus不同的是:

  • 传入的参数为正数时,表示减少年份
  • 传入的参数为负数时,表示增加年份

代码示例:

public static void main(String[] args) {
        //先创建一个LocalDateTime对象:2020,11,11,13:14:15
        LocalDateTime localDateTime = LocalDateTime.of(2020, 11, 11, 13, 14, 15);
        //传入参数-1,因为minus与plus方法相反,参数为负数时,表示增加相应的时间,所以这里表示年数增加1
        LocalDateTime minus = localDateTime.minusYears(-1);
        //再格式化一下
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String s = minus.format(pattern);
        System.out.println(s);
        //输出2021-11-11 13:14:15
    }

增加月份、天数、小时、分钟等,都是调用相应的方法:

二、 LocalDateTime中直接修改时间的方法

1.使用with方法直接修改时间:

代码示例:

public static void main(String[] args) {
        //先创建一个LocalDateTime对象:2020,11,11,13:14:15
        LocalDateTime localDateTime = LocalDateTime.of(2020, 11, 11, 13, 14, 15);
        //调用withYear()方法,参数传入想要修改成的时间,这里修改年份为2022
        LocalDateTime newLocalDateTime1 = localDateTime.withYear(2022);
        //再格式化一下
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String s = newLocalDateTime1.format(pattern);
        System.out.println(s);
    }

直接修改月份、天数、小时、分钟等,都是调用相应的方法:

三、LocalDateTime中计算时间间隔的方法

1.使用**Period.between(开始时间,结束时间)**方法获取时间间隔的年月日:

注: Period.between中传入的参数是LocalDate型 的对象, LocalDate型只包含年月日
步骤:

  • 先创建两个LocalDate对象
  • 再使用Period调用between方法,传入两个LocalDate对象参数,再传给Period对象
  • 再使用period对象调用获取相应时间的方法

代码示例:

public static void main(String[] args) {
        //先创建LocalDate对象
        LocalDate localDate1 = LocalDate.of(2020, 1, 1);
        LocalDate localDate2 = LocalDate.of(2022, 1, 1);
        //再使用Period调用between方法,传给Period对象
        Period period = Period.between(localDate1, localDate2);
        //再使用period对象调用获取相应时间的方法
        //获取相差的年份
        int periodYears = period.getYears();
        //获取相差的月份
        int periodMonths = period.getMonths();
        //获取相差的天数
        int periodDays = period.getDays();
        System.out.println("相差" + periodYears + "年" + periodMonths + "月" + periodDays + "日");
        //输出:相差2年0月0日
    }

2.使用**Duration.between(开始时间,结束时间)**方法 获取时间间隔的秒、毫秒、纳秒

注: Duration.between中传入的参数是LocalDateTime型 的对象, LocalDateTime型包含年月日时分秒
步骤:

  • 先创建两个LocalDateTime对象
  • 再使用Duration调用between方法,传入两个LocalDateTime对象参数,再传给Duration对象
  • 再使用Duration对象调用获取相应时间的方法

代码示例:

	LocalDateTime localDateTime1 = LocalDateTime.of(2022, 11, 11, 13, 14, 15);
        LocalDateTime localDateTime2 = LocalDateTime.of(2023, 11, 11, 13, 15, 15);
        Duration duration = Duration.between(localDateTime1, localDateTime2);
        long seconds = duration.toSeconds();
        long millis = duration.toMillis();
        long nanos = duration.toNanos();
        System.out.println("相差" + seconds + "秒,即" + millis + "毫秒,即" + nanos + "纳秒");

DateTimeFormatter 日期时间格式化器

DateTimeFormatter是在Java 8中引入的一个格式化器,用于打印和解析日期时间对象。

DateTimeFormatter是不可变的,并且是线程安全的。

DateTimeFormatter使用用户定义的格式(如 "yyyy-MMM-dd hh:mm:ss")或使用预定义的常数(如ISO_LOCAL_DATE_TIME)来格式化日期时间。

一个DateTimeFormatter可以用所需的LocaleChronologyZoneIdDecimalStyle创建。

DateTimeFormatter通过使用其ofPattern方法被实例化为一个日期时间格式字符串。

实例化DateTimeFormatter

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MMM-dd HH:mm:ss"); 

查找代码,用给定的格式打印日期时间(date-time)对象的代码。

String dateTime = formatter.format(LocalDateTime.now());
System.out.println(dateTime); //2018-Dec-21 11:14:12 

查找代码,用给定的格式解析一个日期时间(date-time)对象。

LocalDateTime ldt = LocalDateTime.parse("2018-Dec-20 08:25:30", formatter);
System.out.println(ldt); //2018-12-20T08:25:30

下面,我们将讨论DateTimeFormatter的方法,并举例说明LocalDateLocalDateTimeLocalTime实例的格式。

  1. ofPattern(String pattern) : 使用给定的模式创建格式化器。

  2. ofPattern(String pattern, Locale locale) : 使用给定的模式和区域设置创建格式化器。

  3. ofLocalizedDate(FormatStyle dateStyle) : 创建具有当地特定日期格式的格式化器。FormatStyle是一个枚举,其值可以是FULL, LONG, MEDIUM, SHORT

  4. ofLocalizedDateTime(FormatStyle dateTimeStyle) : 创建具有特定地区日期时间(date-time)格式的格式化器。

ofLocalizedDateTime(FormatStyle dateStyle, FormatStyle timeStyle) : 创建具有特定地区日期时间(date-time)格式的格式化器。我们需要为日期和时间分别传递FormatStyle。例如,日期可以是LONG,时间可以是SHORT

  1. ofLocalizedTime(FormatStyle timeStyle) : 创建具有当地特定时间格式的格式化器。
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Locale;

public class DateTimeFormatterDemo {
  public static void main(String[] args) {
	LocalDate localDate = LocalDate.now();

	DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("MMM dd, yyyy");
	String formattedDate1 = formatter1.format(localDate);
	System.out.println(formattedDate1); //Dec 17, 2018

	DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("MMM dd, yyyy", Locale.CANADA);
	String formattedDate2 = formatter2.format(localDate);
	System.out.println(formattedDate2); //Dec. 17, 2018 

	DateTimeFormatter formatter3 = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
	String formattedDate3 = formatter3.format(localDate);
	System.out.println(formattedDate3); //Monday, December 17, 2018

	LocalDateTime localDateTime = LocalDateTime.now();

	DateTimeFormatter formatter4 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
	String formattedDate4 = formatter4.format(localDateTime);
	System.out.println(formattedDate4); //Dec 17, 2018, 9:14:39 PM

	DateTimeFormatter formatter5 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG, FormatStyle.SHORT);
	String formattedDate5 = formatter5.format(localDateTime);
	System.out.println(formattedDate5); //December 17, 2018, 9:14 PM

	LocalTime localTime = LocalTime.now();

	DateTimeFormatter formatter6 = DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM);
	String formattedDate6 = formatter6.format(localTime);
	System.out.println(formattedDate6); //9:14:39 PM
  }
} 

输出

Dec 17, 2018
Dec. 17, 2018
Monday, December 17, 2018
Dec 17, 2018, 9:14:39 PM
December 17, 2018, 9:14 PM
9:14:39 PM 

FormatStyle:

它是一个关于本地化日期、时间或日期时间(date-time)格式化风格的枚举。

它有以下常数。

  1. FULL :例如 'Tuesday, April 11, 2015 AD' or '5:30:45pm PST'.
  2. LONG :例如 'January 10, 2018'.
  3. MEDIUM :例如 'Jan 10, 2018'
  4. SHORT :例如 '11.15.50' or '6:30pm'.

DateTimeFormatter format() 和 formatTo()。

为了格式化一个日期、时间或日期时间(date-time),DateTimeFormatter提供了以下方法。

  1. format(TemporalAccessor temporal) : 使用该格式化器对给定的日期时间(date-time)对象进行格式化,并以字符串形式返回。
  2. formatTo(TemporalAccessor temporal, Appendable appendable) : 使用该格式化器对给定的日期时间(date-time)对象进行格式化,并将结果附加到给定的Appendable对象中。Appendable对象可以是StringBufferStringBuilder等的实例。
  3. import java.time.LocalDateTime;
    import java.time.format.DateTimeFormatter;
    public class DateTimeFormatterDemo {
      public static void main(String[] args) {
         DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MMM-dd hh:mm:ss");
         LocalDateTime ldt = LocalDateTime.now();
         System.out.println(dtf.format(ldt)); //2018-Dec-20 03:50:45
    
         StringBuffer sb = new StringBuffer("Date ");
         dtf.formatTo(ldt, sb);
         System.out.println(sb); //Date 2018-Dec-20 03:50:45
      }
    } 
    

【Java 8 新特性】Java DateTimeFormatter 日期时间格式化器_猫巳的博客-CSDN博客


标题:LocalDateTime中增加、减少、直接修改时间的方法、计算时间间隔的方法
作者:llilei
地址:http://solo.llilei.work/articles/2023/12/01/1701395716031.html