Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Output date as YYYY-MM-DD

Tags:

java

date

getter

I have a getter in Java 8 that I set to the below, problem is the output is Sat Jan 11 00:00:00 AEDT 2020

The class has to remain as a Date, StartDate is a LocalDate.

public static Date getStartDate() {
    return Date.from(StartDate.atStartOfDay()
                      .atZone(ZoneId.systemDefault())
                      .toInstant());
}

I need it to return the value as YYYY-MM-DD and I am struggling to work it out.

Yes, this is an assignment. No idea on the logic where we've been told to set one to Date and the other as LocalDate, other than to annoy me......

Any help appreciated.

like image 518
user10631180 Avatar asked Sep 01 '25 02:09

user10631180


1 Answers

Please try this solution.

public static String getStartDate() {
    DateTimeFormatter oldPattern = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSz");
    DateTimeFormatter newPattern = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    LocalDateTime datetime = LocalDateTime.parse(new Date().toInstant().toString(), oldPattern);
    return datetime.format(newPattern);
}
like image 84
Naveen Avatar answered Sep 02 '25 14:09

Naveen