2

I have a string for a time in the format "HH:mm" and I would like to get Joda's DateTime for that in the near future. For instance, if now would be 16:33 of March/28, and I give the string "5:10", then I would want to get a DateTime that is "2014-03-29 05:10", i.e., tomorrow at 5 AM, not today at 5 AM.

I'm trying to get a one-liner code to do that (because Joda is good for one-liners), in this style:

String input = "16:33";
DateTime dt = ... // Do fancy Joda one-liner
assert dt.isAfterNow() == true;

Sounds very simple, and I can do it in about 20 lines of code, I just thought there has to be a clever way of doing this.

But I would also be satisfied with a one-liner for a similar case:

int hour = 16;
int minute = 33;
DateTime dt = ... // Do fancy Joda one-liner
assert dt.isAfterNow() == true;
André Staltz
  • 13,304
  • 9
  • 48
  • 58
  • Do you mean something like this? http://stackoverflow.com/questions/16461361/add-one-day-into-joda-time-datetime – Software Engineer Mar 28 '14 at 14:45
  • No, because if the current time is `"15:01"` and I input `"16:33"` then both should be in the same day. I'm interested in getting the nearest instant in the future. – André Staltz Mar 28 '14 at 14:51

1 Answers1

1

Well, it sounds like it would be a good idea to separate this into more appropriate types:

LocalTime userTime = ...; // Parse the user input
DateTime now = DateTime().now();
LocalDate today = now.toLocalDate();
LocalDate resultDate = now.toLocalTime().isBefore(userTime) ? today : today.plusDays(1);
DateTime result = resultDate.toDateTime(userTime, now.getTimeZone());
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194