Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the start and end time of a period?

I have an enum TimeFrame that has values like: Yesterday, LastWeek, NextMonth etc.

I'm trying to write a method that takes in a TimeFrame and returns the start and end dates of that period of time.

I looked into the new Java 8 Period class which can take a start time and end time but it doesn't seem there's any clean way to retrieve those values afterwards.

How could I return the start and end date at once cleanly without using a List (seems like the wrong data structure) or some ugly datetime arithmetic?

like image 820
Mike Medina Avatar asked Jun 22 '16 17:06

Mike Medina


1 Answers

No, a Period doesn't record a start/end - it just represents the amount of time between them, in a calendrical sense (rather than the "precise amount of time" represented by a Duration).

It sounds like basically you should create your own class that has a start date and an end date. You can still use Period to implement that, but you'd have getStartDate() and getEndDate() returning LocalDate values. You shouldn't need to do any heavy date/time arithmetic yourself - just work out the start date and add the appropriate period, or the end date and subtract the appropriate period, depending on the time frame.

like image 172
Jon Skeet Avatar answered Sep 25 '22 13:09

Jon Skeet