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.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With