从当前日期时间中减去1年,格式为yyyy-MM-dd HH:mm:ss.SSS。

huangapple go评论87阅读模式
英文:

Get 1 year back dateTime from current dateTime in yyyy-MM-dd HH:mm:ss.SSS format

问题

我需要获取当前日期的1年前的日期时间,格式应为"yyyy-MM-dd HH:mm:ss.SSS"。

  • 例如:2019-08-13 12:00:14.326

我尝试了以下方法,但出现错误:

LocalDate now = LocalDate.now();
LocalDate localDate = LocalDate.parse(now.toString(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")).minusYears(1);

返回以下异常信息:

DateTimeParseException: 无法解析文本 '2020-08-13'

在Java 8+ 中,最佳方式是如何实现这个目标?

英文:

I need to get the datetime of 1 year back considering the current datetime. The format needed to be in "yyyy-MM-dd HH:mm:ss.SSS"

  • ex : 2019-08-13 12:00:14.326

I tried following. But getting an error.

LocalDate now = LocalDate.now();
LocalDate localDate = LocalDate.parse(now.toString(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")).minusYears(1);

Below Exception returned:

> DateTimeParseException: Text '2020-08-13' could not be parsed

What's the best way to do this in Java 8+ ?

答案1

得分: 3

LocalDate不包含有关小时、分钟、秒或更低单位的信息,而是包含年、月和日的信息。通过调用LocalDate.now(),您将获得今天的日期(代码执行的日期)。

如果您还需要时间信息,请使用LocalDateTime,它也有一个now()方法,实际上由LocalDateLocalTime组成。

您的错误消息告诉您,无法使用给定的模式("yyyy-MM-dd HH:mm:ss.SSS")格式化LocalDate的内容,因为该模式需要小时(HH)、分钟(mm)、秒(ss)和毫秒(SSS秒的小数,三个组合在一起表示毫秒)的值。

对于解析字符串或格式化日期时间,LocalDateTime可能是合适的,但如果您想可靠地添加或减去一年或任何其他时间量,您最好使用考虑时区、偏移和夏令时的类,如ZonedDateTimeOffsetDateTime...

英文:

A LocalDate does not hold any information about hours, minutes, seconds or any unit below, instead, it holds information about year, month and day. By calling LocalDate.now() you are getting the date of today (the day of code execution).

If you need the time as well, use a LocalDateTime, which has a method now(), too, and actually consists of a LocalDate and a LocalTime.

Your error message tells you that the content of a LocalDate cannot be formatted using the given pattern (-String) "yyyy-MM-dd HH:mm:ss.SSS" because that pattern requires values for hours (HH), minutes (mm), seconds (ss) and milliseconds (SSS are fraction of seconds and three of them make it be milliseconds).

For parsing Strings or formatting datetimes, a LocalDateTime may be suitable but if you want to reliably add or subtract a year or any other amount of time, you'd rather use a class that considers time zones, offsets and daylight saving like ZonedDateTime or OffsetDateTime...

答案2

得分: 2

不一定是“最佳”方法,但这样做可以:

LocalDateTime date = LocalDateTime.now().minusYears(1);

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

System.out.println(date.format(formatter));
英文:

May not be the best way, but this will do it

LocalDateTime date = LocalDateTime.now().minusYears(1);

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

System.out.println(date.format(formatter));

答案3

得分: 2

LocalDate不适合您的需求,因为它不包含时间信息。您可以使用LocalDateTime,但我建议您使用OffsetDateTimeZonedDateTime,以便可以灵活使用Zone Offset和Zone ID。请查看https://docs.oracle.com/javase/tutorial/datetime/iso/overview.html,了解有关日期时间类的概述。

另外,请记住,日期、时间或日期时间对象只是保存日期/时间信息的对象;它们不包含任何关于格式化的信息,因此无论您在打印它们的对象时采取什么操作,您总是会得到它们的toString()方法返回的输出。为了格式化这些类,换句话说,为了获得表示这些对象的自定义格式的字符串,您可以使用格式化API(例如现代的DateTimeFormatter或传统的SimpleDateFormat)。

一个示例代码:

import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        // 获取当前日期和时间在UTC
        OffsetDateTime odtNow = OffsetDateTime.now(ZoneOffset.UTC);
        System.out.println("Now at UTC: " + odtNow);

        // 获取一年前的日期和时间在UTC
        OffsetDateTime odtOneYearAgo = odtNow.minusYears(1);
        System.out.println("One year ago at UTC: " + odtNow);

        // 为所需模式定义一个格式化程序
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");

        // 使用您定义的格式化程序格式化日期和时间
        String formattedDateTimeOneYearAgo = formatter.format(odtOneYearAgo);
        System.out.println("Date Time in the pattern, yyyy-MM-dd HH:mm:ss.SSS: " + formattedDateTimeOneYearAgo);
    }
}

输出:

Now at UTC: 2020-08-13T08:50:36.277895Z
One year ago at UTC: 2020-08-13T08:50:36.277895Z
Date Time in the pattern, yyyy-MM-dd HH:mm:ss.SSS: 2019-08-13 08:50:36.277
英文:

The LocalDate is the wrong class for your requirement as it does not hold the time information. You can use LocalDateTime but I suggest you use OffsetDateTime or ZonedDateTime so that you can get the flexibility of using the Zone Offset and Zone ID. Check https://docs.oracle.com/javase/tutorial/datetime/iso/overview.html for an overview of date-time classes.

Also, keep in mind that a date or time or date-time object is an object that just holds the information about date/time; it doesn't hold any information about formatting and therefore no matter what you do when you print their objects, you will always get the output what their toString() methods return. In order to format these classes or in other words, to get a string representing a custom format of these objects, you have formatting API (e.g. the modern DateTimeFormatter or legacy SimpleDateFormat) at your disposal.

A sample code:

import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

public class Main {
	public static void main(String[] args) {
		// Get the current date & time at UTC
		OffsetDateTime odtNow = OffsetDateTime.now(ZoneOffset.UTC);
		System.out.println("Now at UTC: " + odtNow);

		// Get the date & time one year ago from now at UTC
		OffsetDateTime odtOneYearAgo = odtNow.minusYears(1);
		System.out.println("One year ago at UTC: " + odtNow);

		// Define a formatter for the output in the desired pattern
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");

		// Format the date & time using your defined formatter
		String formattedDateTimeOneYearAgo = formatter.format(odtOneYearAgo);
		System.out.println("Date Time in the pattern, yyyy-MM-dd HH:mm:ss.SSS: " + formattedDateTimeOneYearAgo);
	}
}

Output:

Now at UTC: 2020-08-13T08:50:36.277895Z
One year ago at UTC: 2020-08-13T08:50:36.277895Z
Date Time in the pattern, yyyy-MM-dd HH:mm:ss.SSS: 2019-08-13 08:50:36.277

答案4

得分: 1

你说你想要一年前的日期+时间,但你只提供了一个日期(LocalDate)。如果你只想要日期,你只需要做以下操作:

LocalDate now = LocalDate.now();
LocalDate then = now.minusYears(1);

如果你也想要时间戳,那么:

LocalDateTime now = LocalDateTime.now();
LocalDateTime then = now.minusYears(1);

其他对象类似。

英文:

You say you want date+time from 1 year back, but you give it only a date (LocalDate). If you just want the date, all you need to do is:

    LocalDate now = LocalDate.now();
    LocalDate then = now.minusYears(1);

And if you want the timestamp also, then:

    LocalDateTime now = LocalDateTime.now();
    LocalDateTime then = now.minusYears(1);

And so on for other objects.

答案5

得分: 1

如前所述,您应该使用 LocalDateTime 而不是 LocalDate。

您的异常是因为您的输入字符串采用了 ISO_DATE_TIME 格式。

Java 文档

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
String now = dateTimeFormatter.format(LocalDateTime.now());
LocalDateTime localDate = LocalDateTime.parse(now, dateTimeFormatter);
英文:

As mentioned you should use LocalDateTime instead of LocalDate.

Your exception was thrown because your input String is in ISO_DATE_TIME format

Java Doc

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
String now = dateTimeFormatter.format(LocalDateTime.now());
LocalDateTime localDate = LocalDateTime.parse(now, dateTimeFormatter);

huangapple
  • 本文由 发表于 2020年8月13日 14:43:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/63389522.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定