Date in string to LocalDateTime conversion in java

challengeAccepted

DateTimes in different formats is always a problem for me. I have a date with the datatype string like "2021-07-25"

I want to convert this date to the datatype LocalDateTime in the format 2021-07-25T00:00:00.000-05:00. I have the get and set property like below

private LocalDateTime relationshipStatusDate;

public LocalDateTime getRelationshipStatusDate() {
    return relationshipStatusDate;
}

public void setRelationshipStatusDate(LocalDateTime relationshipStatusDate) {
    this.relationshipStatusDate = relationshipStatusDate;
}


public void setRelationshipStatusDate(String time) {
    if (time != null) {
        try {
            long epochTime = Long.parseLong(time);
            this.relationshipStatusDate = LocalDateTime.ofInstant(Instant.ofEpochMilli(epochTime), ZoneOffset.UTC);
        } catch (NumberFormatException e){
            this.relationshipStatusDate = LocalDateTime.parse(time, DateTimeFormatter.ISO_DATE_TIME);
        }
    }
}

and I am trying to format like below and its failing with an error "Unknown pattern letter T"

  DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-ddT00:00:00.000-05:00");
  LocalDateTime dateTime = LocalDateTime.parse(statusDate, formatter);
Thomas

Your format won't be parsable as it doesn't support default values like T00:00:00.000-05:00. You could escape literals e.g. use 'T00:00...' but that would just make the parser ignore them.

Instead, if all you get is a date then only parse a date and add the default time after that, e.g. like this:

 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")    
 LocalDate date = LocalDate.parse(statusDate, formatter );
 LocalDateTime dateTime = date.atStartOfDay(); //"relative" representation as the absolute instant would require adding a timezone
 ZonedDateTime zonedDT = date.atSTartOfDay(ZoneOffset.UTC); //"absolute" representation of instant

I want to convert this date to the datatype LocalDateTime in the format 2021-07-25T00:00:00.000-05:00.

Note the potential misconception here: LocalDateTime does NOT have a format. It represents a date and time (from a local point of reference - not in absolute terms as the timezone is missing) and provides access to individual fields such as day of month, day of week etc. but it is not formatted. Formatting is applied when you convert that date object to a string.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

TOP Ranking

HotTag

Archive