Home > Mobile >  spring json parsed Date contains hours
spring json parsed Date contains hours

Time:05-06

I got a spring application that has uses an Entity like this:

@Getter
@Setter
class Entity {
    private Date delay;
}

I pass the folloging json to an spring endpoint.

{
  "delay": "2022-05-15"
}

When I call entity.getDelay().getTime() I get 1652572800 this is the passed date plus 2 hours.

I want to receive the date with 0 hours because I need to compare the value to a value in a database that is stored without hours and minutes.

I you know how to achieve this?

CodePudding user response:

Java 8 brought a lot of language improvements. One of those is the new Date and Time API for Java. The new Date and Time API is moved to java.time package. The new java.time package contains all the classes for date, time, date/time, time zones, instants, duration, and clocks manipulation.

Example classes:

  • Clock
  • LocalDate
  • LocaleTime
  • LocalDateTime
  • Duration

Example using LocalDate

public class YourDto {

    private LocalDate delay;
........//todo
}

Find your day, year, and month like below

   //Using LocalDate

    // Month value
    (dto.getDelay().getMonth().getValue()); == 5

    // Month
    (dto.getDelay().getMonth()); == May

    // Day
    (dto.getDelay().getDayOfMonth()); == 15

    // Year
    (dto.getDelay().getYear()); == 2022

    // Date
    (dto.getDelay()); == 2022-05-15

Convert LocalDate to Milliseconds and Vice versa

       // Convert LocalDate to Milliseconds
        long time = dto.getDelay().atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli();
        System.out.println("Time in millisecoinds = "   time);
        // Convert Milliseconds to LocalDate
        LocalDate myDate = LocalDate.ofEpochDay(Duration.ofMillis(time).toDays());
        System.out.println("LocalDate = "   myDate);    

As per @Ole V.V. suggestion.

// Convert Milliseconds to LocalDate
    LocalDate myDate = Instant.ofEpochMilli(time).atOffset(ZoneOffset.UTC).toLocalDate();

UTC is not a time zone, but a time standard that is the basis for civil time and time zones worldwide.

Ref

  • Related