简体   繁体   中英

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

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+?

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 String s 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 ...

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));

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 (eg 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

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM