I tried looking at this link for inspiration: Parsing a date’s ordinal indicator ( st, nd, rd, th ) in a date-time string
However I am getting an error when I try to parse a string "Mon 21st May" to "Monday 21st May" - full day name, date number and full month.
Exception in thread "main" java.time.format.DateTimeParseException: Text 'Mon 21st May' could not be parsed at index 0 at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949) at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851) at java.time.LocalDate.parse(LocalDate.java:400) at HelloWorld.main(HelloWorld.java:45)
Here is the code:
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
// one class needs to have a main() method
public class HelloWorld
{
// arguments are passed using the text field below this editor
public static void main(String[] args) throws Exception
{
String str = "Mon 21st May";
DateTimeFormatter parseFormatter = DateTimeFormatter.ofPattern("EEEE d['st']['nd']['rd']['th'] MMMM", Locale.ENGLISH);
LocalDate datetext = LocalDate.parse(str, parseFormatter);
}
}
UPDATE:
Here is the latest code I have tried following suggestions and I changed the string to see if the issue is with that and below is there error I now receive. Looks like it knows the dates, just not able to parse it:
public static void main(String[] args) throws Exception
{
String str = "Tue 21st May";
DateTimeFormatter parseFormatter = DateTimeFormatter.ofPattern("EEE d['st']['nd']['rd']['th'] MMMM", Locale.ENGLISH);
LocalDate datetext = LocalDate.parse(str, parseFormatter);
}
}
Error:
Exception in thread "main" java.time.format.DateTimeParseException: Text 'Tue 21st May' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {DayOfWeek=2, DayOfMonth=21, MonthOfYear=5},ISO of type java.time.format.Parsed at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920) at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855) at java.time.LocalDate.parse(LocalDate.java:400) at HelloWorld.main(HelloWorld.java:26) Caused by: java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: {DayOfWeek=2, DayOfMonth=21, MonthOfYear=5},ISO of type java.time.format.Parsed at java.time.LocalDate.from(LocalDate.java:368) at java.time.format.Parsed.query(Parsed.java:226) at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851) ... 2 more