Pergunta

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;
Foi útil?

Solução

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());
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top