Search by multiple datetime units - java

In a form, I have 4 fields where the user can select the date in a list to search for an event that happened on that date:
year
month
day
hour
So far it works only when none of the fields is selected (so the result is all the events that ever happened), or only when all fields are selected (so the result is all events that happened in that hour of that day of that month of that year).
My problem is that I don't know how to search if only a month or a year and an hour is selected (all 4^4 combinations possible). How can I achieve this?

Your Question is vague as it does not address your goal. I will assume you are gathering input for some kind of query against a date range.
So I suppose it makes sense to have a year alone, or a year+month, or a year+month+dayOfMonth, or a year+month+dayOfMonth+Hour but no other combinations.
Date-time values
Use the java.time classes to determine dates or date-times for searching.
For year only, use Year class.
if( yearOnly ) {
Year year = Year.of( Integer.intValue( yearFieldValue ) );
LocalDate yearStartDate = year.atDay( 1 );
LocalDate yearStopDate = year.atDay( year.length() ); // Year is normally 365 or 366 days long ([Leap Year][2]).
}
Or if you are wisely using the Half-Open approach to defining a span of time, where the beginning is inclusive while the ending is exclusive that would mean a year starts on the first of the year and runs up to, but does not include, the first of the following year.
if( yearOnly ) {
Year year = Year.of( Integer.intValue( yearFieldValue ) );
LocalDate targetYearStartDate = year.atDay( 1 );
LocalDate followingYearStartDate = targetYearStartDate.plusYears( 1 );
}
If you need exact moments, get the first moment of each day. Specify a time zone as when the date starts varies around the globe by zone. Apply a ZoneId to get a ZonedDateTime object.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdtStart = targetYearStartDate.atStartOfDay( z );
ZonedDateTime zdtStop = followingYearStartDate.atStartOfDay( z );
If they provide year and month but no date and no hour, use YearMonth.
YearMonth ymStart = YearMonth.of( Integer.intValue( yearFieldValue ) , Integer.intValue( monthFieldValue ) );
LocalDate ldStart = ymStart.atDay( 1 );
LocalDate ldStop = ym.plusMonths( 1 ).atDay( 1 );
If you get year and month and day-of-month, do straight to a LocalDate.
LocalDate ld = LocalDate.of(
Integer.intValue( yearFieldValue ) ,
Integer.intValue( monthFieldValue ) ,
Integer.intValue( dayOfMonthFieldValue )
)
If you also get an hour, then construct a LocalTime. Combine with LocalDate and ZoneId to get a ZonedDateTime object.
LocalTime lt = LocalTime.of( Integer.intValue( hourFieldValue ) , 0 );
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z );
User Interface
In terms of user interface, you could enable only the year field at first. Once a valid value is entered, enable the next field, and so on.
If you cannot do that, then one approach is to not address bad entries. If they enter year and dayOfMonth but no month, just go with searching for the entire year, for example.
If you want to address bad data entry, then you need to do the checking with your code, looking for each good and bad combination.

Related

Get the month last date

I have a LocalDateTime object I want to get the last date of the month. So if the localDateTime points to today's date of 29th October. I want to convert it to 31st October Is there a clean and easy way to do it?
My Thoughts:
One way would be to get the month and then make a switch statement. But that would be the long and tedious approach. Not sure if there is an inbuilt method to do the same
Use YearMonth.atEndOfMonth
LocalDate date = LocalDate.now();
YearMonth month = YearMonth.from(date);
LocalDate end = month.atEndOfMonth();
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
public class Main {
public static void main(String args[]) {
LocalDateTime a = LocalDateTime.of(2021, 10, 29, 0, 0);
LocalDateTime b = a.with(TemporalAdjusters.lastDayOfMonth());
System.out.println(a);
System.out.println(b);
}
}
You asked:
How do I add the endTime of day to the localDateTime. I see an option called LocalTime.MAX but it adds trailing .99999
Do not use LocalDateTime if you are tracking moments, specific points on the timeline. That class lacks the context of a time zone or offset-from-UTC. For moments, use Instant, OffsetDateTime, or ZonedDateTime.
Represent an entire month with YearMonth.
You should not try to nail down the last moment of the month. That last moment is infinitely divisible. Generally, the best way to define a span of time is the Half-Open approach rather than Fully-Closed. In Half-Open, the beginning is inclusive while the ending is exclusive.
So a day starts with first moment of the day and runs up to, but does not include, the first moment of the next day. A month starts with the first moment of the first day of the month and runs up to, but does not include, the first moment of the first of the next month.
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
YearMonth currentMonth = YearMonth.now( z ) ;
YearMonth followingMonth = currentMonth.plusMonths( 1 ) ;
ZonedDateTime start = currentMonth.atDay( 1 ).atStartOfDay( z ) ;
ZonedDateTime end = followingMonth.atDay( 1 ).atStartOfDay( z ) ;
To represent that span of time, add the ThreeTen-Extra library to your project. Use the Interval class with its handy comparison methods such as abuts, overlaps, and contains.
org.threeten.extra.Interval interval = Interval.of( start.toInstant() , end.toInstant() ) ;

Data structure for representing a calendar schedule with a set time granularity?

I've been trying to think of a purely Java way to represent a schedule for a whole calendar year. Each schedule is for a 30 minute slot (half hour granularity).
This would be abstracted through a repository methods like findByDateTime()
Essentially I need to model time slots at 30 min granularites for each day.
The way I have hacked it together is like so
public Map<Integer, Map<Integer, Programme>> enumerateMapOfMapSchedules() {
int numberOfSlots = 48; //48 half hours in a day
Map<Integer, Map<Integer, Programme>> dayToTimeScheduleMap = new HashMap<>();
//create a key value map for each day of the year
for (int i = 1; i < 366; i++) {
Map<Integer, Programme> dayProgrammeScheduleMap = new HashMap<>();
for (int y = 1; y < numberOfSlots; y++) {
dayProgrammeScheduleMap.put(y, null);
}
dayToTimeScheduleMap.put(i, dayProgrammeScheduleMap);
}
//creates a map with 365 days and each day having a map of 48 schedule slots
return dayToTimeScheduleMap;
}
I appreciate this solution doesn't handle or have a concept of year, however since these are for mocks/tests then I am ok with this.
Also it doesn't handle a schedule that overlaps, if programme spans two half hour slots.
My query method is quite simple for finding what is in a particular schedule slot.
public Programme findByDateTime(LocalDateTime dateTime) {
int scheduleSlot = dateTime.getHour() * 2;
//if its the after 30 minute schedule slot
if (dateTime.getMinute() > 30) {
scheduleSlot++;
}
return scheduleMap.get(dateTime.getDayOfYear()).get(scheduleSlot);
}
However for iterating through all the data structure to see how many occurences of a particular programme exist.
My question, is there an easier way of doing this?
I tried doing it with a relational DB but it was hard to represent time periods easily without a lot of SQL.
Any suggestions or implementation advice welcomed!
Days vary in length
A calendar schedule only makes sense in the context of a time zone and a year. Politicians frequently change the offset used by the time zone(s) of their jurisdiction. This means days are not always 24-hours long. Anomalies such as Daylight Saving Time (DST) mean a day might be 23 hours long, 25 hours long, or something else such as 23.5 hours long.
Start at the beginning, count by 30-minute increments
So if what you want is to chop up the entire year in 30-minute segments, you must start at the first moment of the first day of a specific year in a specific time zone, and add 30 minutes at a time until reaching the new year.
ZoneId z = ZoneId.of( "America/Montreal" );
Year year = Year.of( 2021 );
LocalDate firstOfYear = year.atDay( 1 );
ZonedDateTime start = firstOfYear.atStartOfDay( z );
List < ZonedDateTime > zdts = new ArrayList <>();
Duration duration = Duration.ofMinutes( 30 );
ZonedDateTime zdt = start;
while ( zdt.getYear() == year.getValue() )
{
zdts.add( zdt );
// Setup the next loop.
zdt = zdt.plus( duration );
}
Return a non-modifiable copy of that list.
List < ZonedDateTime > slots = List.copyOf( zdts );
When run. Notice what happens at 1 or 2 AM on Mar 14, 2021 and Nov 7, 2021.
slots = [2021-01-01T00:00-05:00[America/Montreal], 2021-01-01T00:30-05:00[America/Montreal], 2021-01-01T01:00-05:00[America/Montreal], 2021-01-01T01:30-05:00[America/Montreal], 2021-01-01T02:00-05:00[America/Montreal],
…
2021-03-14T01:00-05:00[America/Montreal], 2021-03-14T01:30-05:00[America/Montreal], 2021-03-14T03:00-04:00[America/Montreal],
…
2021-11-07T00:30-04:00[America/Montreal], 2021-11-07T01:00-04:00[America/Montreal], 2021-11-07T01:30-04:00[America/Montreal], 2021-11-07T01:00-05:00[America/Montreal], 2021-11-07T01:30-05:00[America/Montreal], 2021-11-07T02:00-05:00[America/Montreal],
…
2021-12-31T22:00-05:00[America/Montreal], 2021-12-31T22:30-05:00[America/Montreal], 2021-12-31T23:00-05:00[America/Montreal], 2021-12-31T23:30-05:00[America/Montreal]]
Future projections unreliable!
But beware: politicians frequently change the offset used in a zone! This happens much more often than you likely realize. Politicians have even gotten worse at this reducing their forewarning from years to a few months, or even several weeks as seen recently in Turkey and Morocco, and even no forewarning at all as seen in North Korea.
So you cannot reliably project into the future using the approach seen above.
Slot math
I suppose you could approach the slots-of-year problem in another way. Calculate the number of whole slots during the year this way.
ZoneId z = ZoneId.of( "America/Montreal" );
Year year = Year.of( 2021 );
LocalDate firstOfYear = year.atDay( 1 );
ZonedDateTime start = firstOfYear.atStartOfDay( z );
ZonedDateTime end = start.plusYears( 1 );
Duration slotLength = Duration.ofMinutes( 30 );
long wholeSlotsInYear = Duration.between( start , end ).dividedBy( slotLength );
Then you could jump to a point in the year by multiplying duration, and adding the result to the start of year.
int slotNumber = 22;
Duration jump = slotLength.multipliedBy( slotNumber - 1 ); // Subtract one to change an ordinal number into a zero-based index.
ZonedDateTime slot22 = start.plus( jump );
Appointment book tracking
If you are doing appointments such as at a hair salon or dental clinic, the usual approach is to track a year-month-day with a particular time of day. But track the time zone separately. So use a LocalDateTime with a separate ZoneId in your Java model. In your database table, use a pair of columns, one of type akin to the SQL-standard type TIMESTAMP WITHOUT TIME ZONE and another column of a text type holding the name of the time zone such as America/Montreal or Africa/Tunis.
When building a schedule, apply the zone to determine a moment. In Java, that means applying a ZoneId to a LocalDateTime to get a ZonedDateTime.
You need to be clear on the fundamental idea that a LocalDateTime object does not represent a moment. In our example here, 3 PM on the 23rd of next year could mean 3 PM in Tokyo Japan or 3 PM in Toledo Ohio US, two very different moments several hours apart. A LocalDateTime is inherently ambiguous. Thus the need to store a time zone as well, but kept separate.
LocalDateTime ldt = LocalDateTime.of( 2021 , 1 , 23 , 15 , 0 , 0 , 0 ) ;
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ; // Determine a moment.
See that same moment in UTC by extracting a Instant.
Instant instant = zdt.toInstant() ;

Is there a way I can print all the days between two epoch times in Java?

//[Sat 2018-12-29 13:30:00 UTC]
final long startTs = 1546090200000L
//[Wed 2019-01-02 09:12:00 UTC]
final long endTs = 1546420320000L
Is there a way using LocalDateTime I can print all the days between these two times?
Ideal output would be:
2018-12-29
2018-12-30
2018-12-31
2019-01-01
2019-01-02
You can use LocalDateTime, for example:
LocalDateTime startLDT = LocalDateTime.ofInstant(Instant.ofEpochMilli(startTs), ZoneId.systemDefault());
LocalDateTime endLDT = LocalDateTime.ofInstant(Instant.ofEpochMilli(endTs), ZoneId.systemDefault());
while (startLDT.isBefore(endLDT)) {
System.out.println(startLDT.format(DateTimeFormatter.ISO_LOCAL_DATE));
startLDT = startLDT.plusDays(1);
}
This loop takes milliseconds and creates instances of LocalDateTime. Then at each iteration if earlier date is before later - it's printed in format yyyy-MM-dd and incremented by day.
tl;dr
First, consider the built-in solution shown in Answer by Ole V.V.
Add the ThreeTen-Extra library to your project, for the LocalDateRange class.
LocalDateRange
.of(
Instant
.ofEpochMilli( 1_546_090_200_000L )
.atZone(
ZoneId.of( "America/Toronto" )
)
.toLocalDate() ,
Instant
.ofEpochMilli( 1_546_420_320_000L )
.atZone(
ZoneId.of( "America/Toronto" )
)
.toLocalDate()
)
.stream()
.forEach(
System.out::println
)
;
2018-12-29
2018-12-30
2018-12-31
2019-01-01
org.threeten.extra.LocalDateRange
The excellent Answer by Ole V.V. is correct, and is likely to meet your needs.
But if you find yourself working often with these date ranges, then you might want to learn about the LocalDateRange class found in the ThreeTen-Extra library. This library adds functionality to the java.time classes built into Java.
As discussed in that other Answer, start by parsing your count of milliseconds since first moment of 1970 in UTC into moments represented as Instant objects.
//[Sat 2018-12-29 13:30:00 UTC]
final long startInput = 1_546_090_200_000L ;
//[Wed 2019-01-02 09:12:00 UTC]
final long stopInput = 1_546_420_320_000L ;
Instant startInstant = Instant.ofEpochMilli( startInput ) ;
Instant stopInstant = Instant.ofEpochMilli( stopInput ) ;
startInstant.toString() = 2018-12-29T13:30:00Z
stopInstant.toString() = 2019-01-02T09:12:00Z
Adjust those into the time zone by which you want to perceive the calendar. Remember, for any given moment, the date varies around the globe by time zone. A moment may be “tomorrow” in Tokyo Japan while simultaneously being “yesterday” in Toronto Canada.
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
ZonedDateTime zdtStart = startInstant.atZone( z ) ; // Produce a `ZonedDateTime` object from the `Instant` by applying a `ZoneId`.
zdtStart.toString() = 2018-12-29T22:30+09:00[Asia/Tokyo]
zdtStop.toString() = 2019-01-02T18:12+09:00[Asia/Tokyo]
Extract the date-only portion, without the time-of-day and without the time zone, as LocalDate object.
LocalDate start = zdtStart.toLocalDate() ;
start.toString() = 2018-12-29
stop.toString() = 2019-01-02
Pass both the start and stop LocalDate objects to make a org.threeten.extra.LocalDateRange.
LocalDateRange dateRange = LocalDateRange.of( start , stop ) ;
dateRange.toString() = 2018-12-29/2019-01-02
This LocalDateRange class has many methods for comparisons including contains, encloses, abuts, and overlaps. But for our purpose here, we want to see all the dates in-between. This class can make a stream of LocalDate objects.
Stream < LocalDate > stream = dateRange.stream() ;
From here, use the same .forEach method call to loop as seen in that other Answer.
2018-12-29
2018-12-30
2018-12-31
2019-01-01
Half-open span-of-time
Handling a span-of-time is usually best done using the Half-Open approach where the beginning is inclusive while the ending is exclusive. If you want to use the code above but also want to include the ending date, just add a day: stop = stop.plusDays( 1 ) ;.
LocalDate::datesUntil ➙ stream
Since Java 9 you can use LocalDate.datesUntil() for iterating over a date interval.
//[Sat 2018-12-29 13:30:00 UTC]
final long startTs = 1_546_090_200_000L;
//[Wed 2019-01-02 09:12:00 UTC]
final long endTs = 1_546_420_320_000L;
LocalDate startDate = millisToLocalDate(startTs);
LocalDate endDate = millisToLocalDate(endTs);
startDate.datesUntil( endDate.plusDays(1) ) // Returns a stream.
.forEach( System.out::println ); // Iterates objects in the stream, passing each to `println` method.
Output from this snippet is:
2018-12-29
2018-12-30
2018-12-31
2019-01-01
2019-01-02
I am using the following auxiliary method for converting your counts of milliseconds to LocalDate. I seemed to understand that you wanted to use dates in UTC, so this is what the method does.
private static LocalDate millisToLocalDate(long millisSinceEpoch) {
return Instant.ofEpochMilli(millisSinceEpoch)
.atOffset(ZoneOffset.UTC)
.toLocalDate();
}
datesUntil returns a stream of the dates from start date inclusive to end date exclusive. Since you wanted the end date to be included, we needed to add one day to it before passing it to datesUntil.
Link: Documentation of LocalDate.datesUntil

Java:processing dates

I'm very new to Java. So please bear with me. I have 4 variables:
mode = prior|later|value;(can have either of these 3 values)
occurrence = 2
day = Wednesday
eta = 14:00
I'm trying to implement a method which will return a list date which is based on following criteria:
case 1 : (mode=prior,occurence=2,day=wednesday,eta=14:00)
should return dates of first 2 wednesdays of the next month from current month.
output = [Wed Aug 01 14:00:00 2018, Wed Aug 08 14:00:00 2018]
case 2 : (mode=later,occurence=2,day=wednesday,eta=14:00)
should return dates of last 2 wednesdays of the next month from current month.
output = [Wed Aug 22 14:00:00 2018, Wed Aug 29 14:00:00 2018]
case 3 : (mode=value,occurence=3,day=wednesday,eta=14:00)
should return date of 3rd wednesday of the next month from current month.
output = [Wed Aug 15 14:00:00 2018, Wed Aug 29 14:00:00 2018]
This is what I've done so far,
public static List<Date> getDates(Calendar c, String mode, int occurrence, int dayNo, String eta) {
List<Date> dates = new ArrayList<Date>();
switch(mode) {
case "value": {
String[] times = eta.split(":");
c.set(Calendar.DAY_OF_WEEK, dayNo);
c.set(Calendar.DAY_OF_WEEK_IN_MONTH, occurrence);
c.set(Calendar.MONTH, Calendar.JULY + 1);
c.set(Calendar.YEAR, 2018);
c.set(Calendar.HOUR_OF_DAY, Integer.parseInt(times[0]));
c.set(Calendar.MINUTE, Integer.parseInt(times[1]));
dates.add(c.getTime());
}
}
return dates;
}
Is there a better way of doing what I've done. Also can somebody please help me with implementing the cases 1 and 2 ?
Avoid legacy date-time classes
You are using terrible old date-time classes that were supplanted years ago by the java.time classes.
In particular, the Calendar class (well, actually, GregorianCalendar) is replaced by ZonedDateTime.
Use types (classes)
Use smart objects rather than dumb strings, where feasible. Using appropriate types makes your code more self-documenting, ensures valid values, provides for type-safety, and lets the compiler catch your typos.
In your case, Java already provides types for most of your data. You can make your own type for the “mode”.
The enum facility in Java is much more powerful and flexible than typically seen in other languages. See Oracle Tutorial to learn more. But the basics are simple, as seen here:
public enum Mode {
PRIOR ,
LATER ,
VALUE
}
For day-of-week, use the DayOfWeek enum, pre-defining seven objects, one for each day of the week. For example, DayOfWeek.WEDNESDAY.
For time-of-day, use LocalTime.
LocalTime lt = LocalTime.of( 14 , 0 ) ;
For the current month, use YearMonth class.
Determining the current year-month means determining the current date. Determining the current date requires a time zone. For any given moment, the date varies around the globe by zone.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ; // Or "America/Chicago", etc.
YearMonth ym = YearMonth.now( z ) ;
If you have a LocalDate, you can determine the year-month for it.
YearMonth ym = YearMonth.from( myLocalDate ) ;
I suggest having the calling method determine the YearMonth rather than make this method jump through extra hoops. A general design approach in OOP is to separate, or disentangle, responsibilities. This method we are writing should be concerned with its own needs (a year-month value) and should not have to care about how the calling method arrives at its desired year-month whether that be from current date or current month or last month, etc.
Lastly, if your goal is to get a moment in time (a date with a time-of-day), then you must also specify a time zone. A date+time without the context of a time zone (or offset-from-UTC) has no real meaning.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
So, putting this all together, your method signature could look like this:
public static List< ZonedDateTime > getDates(
YearMonth ym ,
Mode mode ,
int occurrences ,
DayOfWeek dow ,
LocalTime lt ,
ZoneId z
) { …
Logic
The solution to your first two cases, Mode.PRIOR and Mode.LATER, is the use of the TemporalAdjuster interface. Specifically, the implementations found in TemporalAdjusters class can determine the “nth” weekday-of-month such as first Wednesday. Even more specifically:
firstInMonth​( DayOfWeek dayOfWeek )
lastInMonth​( DayOfWeek dayOfWeek )
The main idea here is to start with the first (or last) day-of-week in the month. Then work our way down (up) through the month, week-by-week, adding (subtracting) a week at a time. Repeat for our limit of integer occurrences.
We can do a switch on our Mode enum, as discussed here. Minor point: I would prefer to use Mode.PRIOR syntax rather than just PRIOR, for clarity. However, an obscure technicality in Java forbids that syntax in a switch. So, case PRIOR: not case Mode.PRIOR:, as shown further down in sample code.
We collect our resulting ZonedDateTime objects in a List named moments.
int initialCapacity = 5; // Max five weeks in any month.
List< ZonedDateTime > moments = new ArrayList<>( initialCapacity );
Let’s look at the logic for each of our three modes.
Mode.PRIOR
Get the first day-of-week of the month.
LocalDate firstDowOfMonth = ym.atDay( 1 ).with( TemporalAdjusters.firstInMonth( dow ) );
Work our way down through the month, adding a week at a time.
We might exceed the bounds of the month, going into the following month. So check the YearMonth to see if it is the same as when when started.
for ( int i = 0 ; i < occurrences ; i++ ) {
LocalDate ld = firstDowOfMonth.plusWeeks( i );
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z );
if ( YearMonth.from( zdt ).equals( ym ) ) { // If in same month…
moments.add( zdt );
}
}
Mode.LATER
This case uses the same logic as above, except we start at the bottom of the month and work our way up. Get the last day-of-week of month, then subtract a week at a time.
// Start with last day-of-week in month.
LocalDate lastDowOfMonth = ym.atDay( 1 ).with( TemporalAdjusters.lastInMonth( dow ) );
// Work our way up through the month, subtracting a week at a time.
for ( int i = 0 ; i < occurrences ; i++ ) {
LocalDate ld = lastDowOfMonth.minusWeeks( i );
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z );
if ( YearMonth.from( zdt ).equals( ym ) ) { // If in same month…
moments.add( zdt );
}
}
Because we are going backwards through time, our collection of moments is in reverse chronological order. So, we need to sort to present these in chronological order.
Collections.sort( moments ); // If you want the list to be in chronological order, sort. Otherwise in reverse chronological order for this `Mode.LATER`.
Mode.VALUE
The last case is the simplest: Get the nth day-of-week in the month. That is simply a one-liner.
LocalDate nthDowInMonth = ym.atDay( 1 ).with( TemporalAdjusters.dayOfWeekInMonth( occurrences , dow ) );
Do the usual, make a ZonedDateTime.
ZonedDateTime zdt = ZonedDateTime.of( nthDowInMonth , lt , z );
Verify the month, as the documentation seems to be saying that exceeding the limits of the month takes us into the next month. In such a case, our logic omits the date from our list. So we will be returning moments as an empty list. This means the calling method should check for the list having elements, as it may be empty.
if ( YearMonth.from( zdt ).equals( ym ) ) { // If in same month…
moments.add( zdt );
}
Let’s see all the code put together.
// Simulate arguments passed.
LocalTime lt = LocalTime.of( 14 , 0 );
ZoneId z = ZoneId.of( "Africa/Tunis" ); // Or "America/Chicago", etc.
YearMonth ym = YearMonth.now( z );
DayOfWeek dow = DayOfWeek.WEDNESDAY;
Mode mode = Mode.PRIOR ; // Mode.PRIOR, Mode.LATER, Mode.VALUE.
int occurrences = 3; // TODO: Add code to verify this value is in range of 1-5, not zero, not >5.
// Logic
int initialCapacity = 5; // Max five weeks in any month.
List< ZonedDateTime > moments = new ArrayList<>( initialCapacity );
switch ( mode ) {
case PRIOR:
// Start with first day-of-week in month.
LocalDate firstDowOfMonth = ym.atDay( 1 ).with( TemporalAdjusters.firstInMonth( dow ) );
// Work our way down through the month, adding a week at a time.
for ( int i = 0 ; i < occurrences ; i++ ) {
LocalDate ld = firstDowOfMonth.plusWeeks( i );
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z );
if ( YearMonth.from( zdt ).equals( ym ) ) { // If in same month…
moments.add( zdt );
}
}
break;
case LATER:
// Start with last day-of-week in month.
LocalDate lastDowOfMonth = ym.atDay( 1 ).with( TemporalAdjusters.lastInMonth( dow ) );
// Work our way up through the month, subtracting a week at a time.
for ( int i = 0 ; i < occurrences ; i++ ) {
LocalDate ld = lastDowOfMonth.minusWeeks( i );
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z );
if ( YearMonth.from( zdt ).equals( ym ) ) { // If in same month…
moments.add( zdt );
}
}
Collections.sort( moments ); // If you want the list to be in chronological order, sort. Otherwise in reverse chronological order for this `Mode.LATER`.
break;
case VALUE:
// Get the nth day-of-week in month.
LocalDate nthDowInMonth = ym.atDay( 1 ).with( TemporalAdjusters.dayOfWeekInMonth( occurrences , dow ) );
ZonedDateTime zdt = ZonedDateTime.of( nthDowInMonth , lt , z );
if ( YearMonth.from( zdt ).equals( ym ) ) { // If in same month…
moments.add( zdt );
}
break;
default: // Defensive programming, testing for unexpected values.
System.out.println( "ERROR - should not be able to reach this point. Unexpected `Mode` enum value." );
break;
}
// return `moments` list from your method.
System.out.println( "moments:\n" + moments );
Note that the specified time-of-day on a particular date in our specified time zone may not be valid. For example, during a cutover in Daylight Saving Time (DST). If so, the ZonedDateTime class adjusts as needed. Be sure to read the documentation to make sure you understand and agree to its adjustment algorithm.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
So as I understand your question I wrote some code for example. I could not understand the "value" option. Desired output and explanation of method is not obvious for me. If you explain it I could edit the answer.
public class Main {
public static void main(String[] args) {
for (String s : findOccurence("prior", DayOfWeek.WEDNESDAY, 2, "14:00")){
System.out.println(s);
}
}
public static String[] findOccurence(String mode, DayOfWeek day, int occurrence, String eta) {
LocalDate now = LocalDate.now();
LocalDate start = LocalDate.of(now.getYear(), now.getMonth().plus(1), 1);
LocalDate finish = start.plusDays(start.lengthOfMonth());
List<LocalDate> dates = Stream.iterate(start, date -> date.plusDays(1))
.limit(ChronoUnit.DAYS.between(start, finish))
.filter(d -> d.getDayOfWeek() == day)
.collect(Collectors.toList());
String[] formattedEta = eta.split(":");
if (occurrence > dates.size()) {
throw new IndexOutOfBoundsException();
}
if (mode.equalsIgnoreCase("value")) {
}
else if (mode.equalsIgnoreCase("later")) {
dates = Lists.reverse(dates);
}
//later and prior shares common logic
return dates.stream()
.limit(occurrence)
.map(d -> day.toString()
+ " "
+ start.getMonth().name()
+ " "
+ d.getDayOfMonth()
+ " "
+ LocalTime.of(Integer.valueOf(formattedEta[0]), Integer.valueOf(formattedEta[1]), 0)
+ " "
+ start.getYear())
.collect(Collectors.toList())
.toArray(new String[occurrence]);
}
}
Output is :
WEDNESDAY AUGUST 1 14:00 2018
WEDNESDAY AUGUST 8 14:00 2018

Java Generate all dates between x and y [duplicate]

This question already has answers here:
how to get a list of dates between two dates in java
(23 answers)
Closed 6 years ago.
I attempted to generate the date range between date x and date y but failed. I have the same method in c# so I tried to modify it as much as I can but failed to get result. Any idea what I could fix?
private ArrayList<Date> GetDateRange(Date start, Date end) {
if(start.before(end)) {
return null;
}
int MILLIS_IN_DAY = 1000 * 60 * 60 * 24;
ArrayList<Date> listTemp = new ArrayList<Date>();
Date tmpDate = start;
do {
listTemp.add(tmpDate);
tmpDate = tmpDate.getTime() + MILLIS_IN_DAY;
} while (tmpDate.before(end) || tmpDate.equals(end));
return listTemp;
}
To be honest I was trying to get all the dates starting from january 1st till the end of year 2012 that is december 31st. If any better way available, please let me know.
Thanks
Joda-Time
Calendar and Date APIs in java are really weird... I strongly suggest to consider jodatime, which is the de-facto library to handle dates.
It is really powerful, as you can see from the quickstart: http://joda-time.sourceforge.net/quickstart.html.
This code solves the problem by using Joda-Time:
import java.util.ArrayList;
import java.util.List;
import org.joda.time.DateTime;
public class DateQuestion {
public static List<DateTime> getDateRange(DateTime start, DateTime end) {
List<DateTime> ret = new ArrayList<DateTime>();
DateTime tmp = start;
while(tmp.isBefore(end) || tmp.equals(end)) {
ret.add(tmp);
tmp = tmp.plusDays(1);
}
return ret;
}
public static void main(String[] args) {
DateTime start = DateTime.parse("2012-1-1");
System.out.println("Start: " + start);
DateTime end = DateTime.parse("2012-12-31");
System.out.println("End: " + end);
List<DateTime> between = getDateRange(start, end);
for (DateTime d : between) {
System.out.println(" " + d);
}
}
}
You could use this function:
public static Date addDay(Date date){
//TODO you may want to check for a null date and handle it.
Calendar cal = Calendar.getInstance();
cal.setTime (date);
cal.add (Calendar.DATE, 1);
return cal.getTime();
}
Found here.
And what is the reason of fail? Why you think that your code is failed?
tl;dr
Year year = Year.of ( 2012 ) ; // Represent an entire year.
year
.atDay( 1 ) // Determine the first day of the year. Returns a `LocalDate` object.
.datesUntil( // Generates a `Stream<LocalDate>`.
year
.plusYears( 1 ) // Returns a new `Year` object, leaving the original unaltered.
.atDay( 1 ) // Returns a `LocalDate`.
) // Returns a `Stream<LocalDate>`.
.forEach( // Like a `for` loop, running through each object in the stream.
System.out :: println // Each `LocalDate` object in stream is passed to a call of `System.out.println`.
)
;
java.time
The other Answers are outmoded as of Java 8.
The old date-time classes bundled with earlier versions of Java have been supplanted with the java.time framework built into Java 8 and later. See Tutorial.
LocalDate (date-only)
If you care only about the date without the time-of-day, use the LocalDate class. The LocalDate class represents a date-only value, without time-of-day and without time zone.
LocalDate start = LocalDate.of( 2016 , 1 , 1 ) ;
LocalDate stop = LocalDate.of( 2016 , 1 , 23 ) ;
To get the current date, specify a time zone. For any given moment, today’s date varies by time zone. For example, a new day dawns earlier in Paris than in Montréal.
LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) );
We can use the isEqual, isBefore, and isAfter methods to compare. In date-time work we commonly use the Half-Open approach where the beginning of a span of time is inclusive while the ending is exclusive.
List<LocalDate> localDates = new ArrayList<>();
LocalDate localDate = start;
while ( localDate.isBefore( stop ) ) {
localDates.add( localDate );
// Set up the next loop.
localDate = localDate.plusDays( 1 );
}
LocalDate::datesUntil
You can obtain a stream of LocalDate objects.
Stream< LocalDate > dates = start.datesUntil( stop ) ;
dates.forEach( System.out::println ) ;
LocalDateRange
If doing much of this work, add the ThreeTen-Extra library to your project. This gives you the LocalDateRange class to represent your pair of start and stop LocalDate objects.
Instant (date-time)
If you have old java.util.Date objects, which represent both a date and a time, convert to the Instant class. An Instant is a moment on the timeline in UTC.
Instant startInstant = juDate_Start.toInstant();
Instant stopInstant = juDate_Stop.toInstant();
From those Instant objects, get LocalDate objects by:
Applying the time zone that makes sense for your context to get ZonedDateTime object. This object is the very same moment on the timeline as the Instant but with a specific time zone assigned.
Convert the ZonedDateTime to a LocalDate.
We must apply a time zone as a date only has meaning within the context of a time zone. As we said above, for any given moment the date varies around the world.
Example code.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate start = ZonedDateTime.ofInstant( startInstant , zoneId ).toLocalDate();
LocalDate stop = ZonedDateTime.ofInstant( stopInstant , zoneId ).toLocalDate();
You can use joda-time.
Days.daysBetween(fromDate, toDate);
Found at joda-time homepage.
similar question in stackoverflow with some good answers.
Look at the Calendar API, particularly Calendar.add().

Categories