-1

I have a value like the following Mon Jun 18 11:32:05 BST 2012 and I want to convert this to 18 June 2012

How to convert this?

Below is what i have tried..

public String getRequiredDate(String sendInputDate) {

Optional<OffsetDateTime> date = dateParsing(sendInputDate);

if(date) { 
     String REQUIRED_PATTERN="dd MMMM yyyy";
     DateTimeFormatter formatter = DateTimeFormatter.ofPattern(REQUIRED_PATTERN);

      return date.get().format(formatter);
    }
  }

import java.time.OffsetDateTime; hence returning in same

public static Optional<OffsetDateTime> dateParsing(String date) {
    String PATTERN = "EEE MMM dd HH:mm:ss zzz yyyy";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(PATTERN);

    return Optional.of(OffsetDateTime.parse(date, formatter));
  }

But its always returning me " " (blank)

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Ravi
  • 25
  • 6
  • What are you using an `Optional` for here? It doesn’t seem that your method can return an empty (non-present) optional, so I cannot see the point? Did you try `ZonedDateTime.parse(date, formatter).toOffsetDateTime()`? Asking because your string contains a time zone abbreviation (`BST`, an ambiguous one, though) and no UTC offset. – Ole V.V. Sep 05 '22 at 11:10
  • In which time zone would you want the resulting date? Asking because at the specified time BST, depending on the interpretation of BST, it’s either June 17 or June 19 in other time zones. And just as important, which time zone is intended by BST? – Ole V.V. Sep 05 '22 at 11:15

1 Answers1

3

It doesn't "return blank". You presumably have some exception handling somewhere which is swallowing the actual issue and replacing that with a blank string.

The actual issue is this exception:

java.time.format.DateTimeParseException: Text 'Mon Jun 18 11:32:05 BST 2012' could not be parsed:
Unable to obtain OffsetDateTime from TemporalAccessor

i.e. your string does not contain an offset, but you are trying to parse it into something which requires one. It has a zone.

You could parse it into a ZonedDateTime and then convert it, for example.

OffsetDateTime parsed = ZonedDateTime.parse(date, formatter).toOffsetDateTime();
Michael
  • 41,989
  • 11
  • 82
  • 128
  • Okay i have edited my question including the complete code tried by me.. – Ravi Sep 05 '22 at 10:54
  • 1
    A time zone and a UTC offset are two very different things. A time zone comprises historic and known future offsets used by the people in a designated area. Since BST refers to some time zone and not to a specific UTC offset, I suppose that Java refuses to derive an `OffsetDateTime` directly from the data from the string. The risk of misinterpreting Bangladesh Standard Time for Bougainville Standard Time or vice versa remains. – Ole V.V. Sep 05 '22 at 11:27
  • Thanks i have accepted this as answer. Its working as expected. Thanks again @Michael – Ravi Sep 05 '22 at 14:52