Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I parse a weekday and time object to the next logical date from today?

Tags:

java

I have a date in the string that looks like MON 07:15. I'm trying to parse this to a Date using this snippet of code:

System.out.println(new SimpleDateFormat("E kk:mm").parse("MON 07:15"));

Using the above code, prints a date that reads:

Mon Jan 05 07:15:00 EET 1970

I'd like the parse the date string to the next upcoming date. At the time of posting, my local date and time is Fri Aug 08 11:45:00 EEST 2014 and the next Monday will be on the 11th so the resultant date that I'm looking for is Mon Aug 11 07:15:00 EEST 2014. How can I parse this?


The day and time object that I'll be parsing will always be in the future.

like image 795
Mridang Agarwalla Avatar asked Mar 19 '23 19:03

Mridang Agarwalla


1 Answers

I would separate parsing from everything else.

Parse the value as you're already doing, which gives you a date in the wrong year.

From that, take the time of day and the day of week - those are the important things. You can throw everything else away.

Next, take the current date and time, and perform whatever operations you need to in order to get to the right date/time. You should consider:

  • What time zone are you interested in?
  • If the current time is 06:00 on a Monday and you've been asked for 07:15 on a Monday, does that mean today or next Monday?
  • If the current time is 08:00 on a Monday and you've been asked for 07:15 on a Monday, does that mean today or next Monday?

By separating out the parsing from the computations, you can make the testing simpler two: test each of the operations separately. I'd advise using a clock abstraction of some kind to indicate "an object which can get you the current instant in time" - that way you can test all kinds of combinations of "desired day/time" and "current day/time".

Ideally, use java.time from Java 8 or Joda Time - both are much nicer than the java.util.* API.

like image 169
Jon Skeet Avatar answered Apr 26 '23 14:04

Jon Skeet