Home > Enterprise >  How to add HH:MM:SS format to the LocalDate in java?
How to add HH:MM:SS format to the LocalDate in java?

Time:11-10

LocalDate beginDate = LocalDate.now()
        .with(ChronoField.DAY_OF_WEEK, 1)
        .atStartOfDay()
        .minusDays(8)
        .toLocalDate();

I am getting the previous week begin date using the above code line. However I want to add HH:MM:SS format to this. I have tried different ways to get this. Tried using LocalDateTime instead of Localdate. But could not find atStartOfDay() method for LocalDateTime. Help me to add HH:MM:SS to beginDate variable

CodePudding user response:

tl;dr

LocalDate                                   // Represents a date only, without a time of day, without a time zone or offset. 
.now( ZoneId.of( "Asia/Tokyo" ) )           // Returns a `LocalDate`. 
.minusDays( 8 )                             // Returns another `LocalDate` object. 
.atStartOfDay( ZoneId.of( "Asia/Tokyo" ) )  // Returns a `ZonedDateTime`. 
.toString()                                 // Returns a `String` object, with text in standard ISO 8601 format wisely extended to append the name of time zone in brackets. 

See this code run at Ideone.com.

2022-11-02T00:00 09:00[Asia/Tokyo]

No “format” involved

Date-time objects do not have a “format”. Text has a format. Date-time objects are not text.

ZonedDateTime

Apparently you want the first moment of the day eight days ago as seen in your locality.

First, specify your desired/expected time zone.

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;

Or use your JVM‘s current default time zone.

ZoneId z = ZoneId.systemDefault() ; 

Capture the current date as seen in that zone.

LocalDate today = LocalDate.now( z ) ;

Go back eight days.

LocalDate eightDaysAgo = today.minusDays( 8 ) ;

If you meant to go back to the previous Monday, use a TemporalAdjuster.

LocalDate previousMonday = today.with( TemporalAdjusters.previous( DayOfWeek.MONDAY ) ) ;

Get the first moment of that day. Pass your time zone.

ZonedDateTime zdt = eightDaysAgo.atStartOfDay( z ) ;

The time-of-day may be 00:00:00, but not necessarily. Some days on some dates in some zones start at another time such as 01:00:00.

All of this has been covered many times already on Stack Overflow. Search to learn more.

CodePudding user response:

What you want is a LocalDateTime, which is a LocalDate with a time component (including timezone).

LocalDate does as it says on the tin, it gives you a date, not a date and time.

CodePudding user response:

LocalDateTime
 .of(LocalDate.now().with(ChronoField.DAY_OF_WEEK, 1), LocalTime.MIDNIGHT)
 .minusWeeks(1)

Gives you start of last week at midnight (local time).

CodePudding user response:

@DateTimeFormat("HH:MM:SS")
@JsonFormat("HH:MM:SS")
  • Related