Always when someone asks a question about dates and/or times in Android, I encourage to check out the ThreeTenABP library. It provides the modern Java date and time classes for Android. These are generally much more programmer friendly than the outdated Date
, SimpleDateFormat
and Calendar
.
I do so even more in your case. You don’t have a year. You may use the not-good old GregorianCalendar
for setting a year, but if the requirements for which year to pick are getting just a little bit complex, you will prefer to work with the modern classes. Here is an example where I find the latest year where the day of week matches the day of week in the string, just as an example, since this probably does not match your exact requirements. I first parse the string into a TemporalAccessor
, I think of this as an intermediate form for creating the object/s we want in the end. From this I take the day of week, month and day and find the year that works. From these pieces we put together a date, and from the parse result we take the time (11:18) and build the LocalDateTime
that is the final result.
String actualDateString = "Saturday, June 10 11:18 AM";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEEE, MMMM dd HH:mm a", Locale.ENGLISH);
// Step one, porse
TemporalAccessor parsed = formatter.parse(actualDateString);
// Use day of week, month and day and find a year that matches
DayOfWeek actualDayOfWeek = DayOfWeek.from(parsed);
MonthDay actualMonthDay = MonthDay.from(parsed);
int cancidateYear = Year.now(ZoneId.systemDefault()).getValue();
while (! actualMonthDay.atYear(cancidateYear).getDayOfWeek().equals(actualDayOfWeek)) {
cancidateYear--;
}
// Final step, put the date and time together from the pieces
LocalDateTime dateTime = LocalDateTime.of(actualMonthDay.atYear(cancidateYear),
LocalTime.from(parsed));
System.out.println(dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
This prints:
2017-06-10 11:18:00
If instead you want the next year where the day of week matches, just count up instead of down in the loop. If needed the modern classes lend themselves well to more elaborate algorithms for determining the year.
Thanks, Hugo, for helping me simplify (once again).
Links