简体   繁体   中英

Finding the Java Date of the next Monday 6:00, for example

I am trying to create some code in Java where someone can determine the date of the next recurring time of the week specified. This is hard to explain so I'll give an example. Say it is March 1st (a Thursday) and the user wants to know when the next Saturday 5:00 is the code should output March 3rd, 5:00 as a Date variable and if it is March 4th, the program should output March 10th and so on...

The user however, can specify what time of the week they want. This is done with a long value which offsets the time of the week from Thursday 0:00 in milliseconds. I'm having trouble wrapping my head around this but this is what I got so far:

public static long findNextTimeOfTheWeek(long offset)
{
    return System.currentTimeMillis() - ((System.currentTimeMillis() - offset) % 604800000) + 604800000;
}

If anyone could help, it would be greatly appreciated. And if any more clarification is needed, just ask. PS 604800000 is the number of milliseconds in a week.

java.time

Using java.time framework built into Java 8.

import java.time.DayOfWeek;
import java.time.LocalDateTime;
import static java.time.temporal.TemporalAdjusters.nextOrSame;

LocalDateTime now = LocalDateTime.now(); // 2015-11-22T09:32:50.045 (Sunday)
now.with(nextOrSame(DayOfWeek.MONDAY));  // 2015-11-23T09:32:50.045 (Monday)

If you really need the next day of week even if your current date satisfies this constraint you may use

import static java.time.temporal.TemporalAdjusters.next;   

now.with(next(DayOfWeek.MONDAY)); // 2015-11-30T09:32:50.045 (Monday)

I suggest you to use Calendar class, you can easily manipulate it and then get a Date object using Calendar#getTime . See the example below, it simply do what you want:

import java.util.Calendar;
import java.util.Locale;
import java.util.Scanner;

public class Main {

    public static int dayOfWeekIWant(final String dayOfWeekIWantString)
            throws Exception {

        final int dayOfWeekIWant;

        if ("sunday".equalsIgnoreCase(dayOfWeekIWantString)) {
            dayOfWeekIWant = Calendar.SUNDAY;
        } else if ("monday".equalsIgnoreCase(dayOfWeekIWantString)) {
            dayOfWeekIWant = Calendar.MONDAY;
        } else if ("tuesday".equalsIgnoreCase(dayOfWeekIWantString)) {
            dayOfWeekIWant = Calendar.TUESDAY;
        } else if ("wednesday".equalsIgnoreCase(dayOfWeekIWantString)) {
            dayOfWeekIWant = Calendar.WEDNESDAY;
        } else if ("thursday".equalsIgnoreCase(dayOfWeekIWantString)) {
            dayOfWeekIWant = Calendar.THURSDAY;
        } else if ("friday".equalsIgnoreCase(dayOfWeekIWantString)) {
            dayOfWeekIWant = Calendar.FRIDAY;
        } else if ("saturday".equalsIgnoreCase(dayOfWeekIWantString)) {
            dayOfWeekIWant = Calendar.SATURDAY;
        } else {
            throw new Exception(
                    "Invalid input, it must be \"DAY_OF_WEEK HOUR\"");
        }

        return dayOfWeekIWant;
    }

    public static String getOrdinal(int cardinal) {
        String ordinal = String.valueOf(cardinal);

        switch ((cardinal % 10)) {
        case 1:
            ordinal += "st";
            break;
        case 2:
            ordinal += "nd";
            break;
        case 3:
            ordinal += "rd";
            break;
        default:
            ordinal += "th";
        }

        return ordinal;

    }

    public static void printDate(Calendar calendar) {
        String dayOfWeek = calendar.getDisplayName(Calendar.DAY_OF_WEEK,
                Calendar.LONG, Locale.ENGLISH);
        String dayOfMonth = getOrdinal(calendar.get(Calendar.DAY_OF_MONTH));
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        System.out.printf("%s %s %02d:%02d", dayOfWeek, dayOfMonth, hour, minute);
    }

    public static void main(String[] args) {

        Calendar calendar = Calendar.getInstance();
        Scanner scanner = new Scanner(System.in);

        final int today = calendar.get(Calendar.DAY_OF_WEEK);

        System.out.println("Please, input the day of week you want to know:");

        boolean inputOk = false;

        while (!inputOk)

            try {
                String input = scanner.nextLine();
                String[] split = input.split("\\s");
                String dayOfWeekIWantString = split[0];

                String[] splitHour = split[1].split(":");
                int hour = Integer.parseInt(splitHour[0]);
                int minute = Integer.parseInt(splitHour[1]);

                int dayOfWeekIWant = dayOfWeekIWant(dayOfWeekIWantString);

                int diff = (today >= dayOfWeekIWant) ? (7 - (today - dayOfWeekIWant))
                        : (dayOfWeekIWant - today);

                calendar.add(Calendar.DAY_OF_WEEK, diff);
                calendar.set(Calendar.HOUR_OF_DAY, hour);
                calendar.set(Calendar.MINUTE, minute);
                calendar.set(Calendar.SECOND, 0);
                calendar.set(Calendar.MILLISECOND, 0);

                inputOk = true;

            } catch (Exception e) {

                // Using a generic exception just for explanation purpose
                // You must create a specific Exception
                System.out
                        .println("Invalid input, you must enter a valid input in format: \"DAY_OF_WEEK HOUR\"");
                continue;
            }

        printDate(calendar);

    }
}

More Information:

You should Calendar class. You specify the date and you cn add days,months or years

   //Here you specify the date the constructor are (year,month,day,hour_od_day,minutes)
        Calendar calendar = new GregorianCalendar(2011, Calendar.MARCH, 1, 5, 0); 
        calendar.add(Calendar.DAY_OF_MONTH, 5); //Adds five days to the date
        switch (calendar.get(Calendar.DAY_OF_WEEK)) { //Tells to the calendar that i want to know the day of the week
            case Calendar.SUNDAY:
                System.out.println("ITS SUNDAY");
                break;
            case Calendar.MONDAY:
                System.out.println("ITS MONDAY");
                break;
            case Calendar.TUESDAY:
                System.out.println("ITS TUESDAY");
                break;
            case Calendar.WEDNESDAY:
                System.out.println("ITS WEDNESDAY");
                break;
            case Calendar.THURSDAY:
                System.out.println("ITS THURSDAY");
                break;
            case Calendar.FRIDAY:
                System.out.println("ITS FRIDAY");
                break;
            case Calendar.SATURDAY:
                System.out.println("ITS SATURDAY");
                break;
        }
        Date date = calendar.getTime(); //Get the Date object
        System.out.println("Date = " + date); //prints the date: 

The result will be: ITS SUNDAY Date = Sun Mar 06 05:00:00 MST 2011

Check the Calendar class: http://docs.oracle.com/javase/6/docs/api/java/util/Calendar.html

If you want to format the Date object check the DateFormat Class: http://docs.oracle.com/javase/6/docs/api/java/text/DateFormat.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM