Phillip
Phillip

Reputation: 457

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 ?

Upvotes: 1

Views: 311

Answers (2)

Basil Bourque
Basil Bourque

Reputation: 339669

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:

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?

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.

Upvotes: 2

Emre Savcı
Emre Savcı

Reputation: 3070

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

Upvotes: 0

Related Questions