例如,查找下周一6:00的Java日期

时间:2012-03-08 02:59:13

标签: java date time

我正在尝试在Java中创建一些代码,以便有人可以确定指定的一周中下一个重复时间的日期。这很难解释,所以我举一个例子。假设它是3月1日(星期四)并且用户想要知道下周六5:00的时间是代码应该输出3月3日,5:00作为Date变量,如果是3月4日,程序应该输出3月10日等等...

然而,用户可以指定他们想要的一周中的哪个时间。这是通过一个长值来完成的,该值可以从星期四0:00(以毫秒为单位)抵消一周的时间。我无法绕过这个,但这是我到目前为止所得到的:

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

如果有人可以提供帮助,我们将不胜感激。如果需要进一步澄清,请问。附: 604800000是一周内的毫秒数。

3 个答案:

答案 0 :(得分:4)

java.time

使用Java 8中内置的java.time框架。

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)

如果您确实需要一周中的第二天,即使您当前的日期满足此约束条件,您也可以使用

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

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

答案 1 :(得分:0)

我建议您使用Calendar类,您可以轻松操作它,然后使用Date获取Calendar#getTime对象。请参阅下面的示例,它只是按照您的意愿执行:

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);

    }
}

更多信息:

答案 2 :(得分:0)

你应该是Calendar课程。您指定日期,并且您可以添加天,月或年

   //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: 

结果将是: 它的星期日 Date = Sun Mar 06 05:00:00 MST 2011

检查日历类:http://docs.oracle.com/javase/6/docs/api/java/util/Calendar.html

如果要格式化Date对象,请检查DateFormat类:http://docs.oracle.com/javase/6/docs/api/java/text/DateFormat.html