将星期几+时间(hh:mm)转换为Java中的日期[复制]

时间:2022-10-21 11:02:35

This question already has an answer here:

这个问题在这里已有答案:

I have "Monday, 9:30" as String, and I want a Date of next Monday with time 9:30 as java.util.Date. How do I do that?

我将“星期一,9:30”作为字符串,我希望下周一的日期时间为9:30,作为java.util.Date。我怎么做?

2 个解决方案

#1


2  

You can create a SimpleDateFormat matching your string. Then you'll use the .parse() method from that class to convert your String to a Date. See this question for a more detailed answer.

您可以创建与字符串匹配的SimpleDateFormat。然后,您将使用该类中的.parse()方法将String转换为Date。有关更详细的答案,请参阅此问题。

Alternately, you can create a Calendar object, and parse your string to set its appropriate fields and then use .getTime() to extract the Date.

或者,您可以创建一个Calendar对象,并解析您的字符串以设置其相应的字段,然后使用.getTime()来提取Date。

EDIT Inspired by Gilbert Le Blanc's answer, I produced his test case much more simply. The steps I used were:

编辑灵感来自Gilbert Le Blanc的回答,我更简单地制作了他的测试用例。我使用的步骤是:

  1. Use SimpleDateFormat to parse the given string including the date, producing a date in 1970.
  2. 使用SimpleDateFormat解析包含日期的给定字符串,在1970年生成日期。

  3. Adjust for any DST offsets
  4. 调整任何DST偏移

  5. Calculate how many weeks in the past the parsed date was.
  6. 计算解析日期过去的周数。

  7. Add this number of weeks to the past date in order to make it the next future date.
  8. 将此周数添加到过去的日期,以使其成为下一个未来日期。

Test output of my program matches Gilbert's (in my time zone):

我的节目的测试输出与吉尔伯特(在我的时区)匹配:

Monday, 9:30 --> Mon May 23 09:30:00 PDT 2016
Friday, 16:45 --> Fri May 20 16:45:00 PDT 2016
Wednesday, 22:15 --> Wed May 18 22:15:00 PDT 2016

You can tweak the approach based on what you really mean by "next". Here's my complete code:

您可以根据“下一步”的真正含义来调整方法。这是我的完整代码:

package foo.bar;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DayTime {

    public static final long MILLISECONDS_PER_WEEK = 7L * 24 * 60 * 60 * 1000;

    public static void main(String[] args) {
        getDate("Monday, 9:30");
        getDate("Friday, 16:45");
        getDate("Wednesday, 22:15");
    }

    private static void getDate(String input) {
        // Parse given date. Convert this to milliseconds since epoch. This will
        // result in a date during the first week of 1970.
        SimpleDateFormat sdf = new SimpleDateFormat("E, H:mm");
        Date date = sdf.parse(input, new ParsePosition(0));

        // Convert to millis and adjust for offset between today's Daylight
        // Saving Time (default for the sdf) and the 1970 date
        Calendar c = Calendar.getInstance();
        int todayDSTOffset = c.get(Calendar.DST_OFFSET);
        c.setTime(date);
        int epochDSTOffset = c.get(Calendar.DST_OFFSET);

        long parsedMillis = date.getTime() + (epochDSTOffset - todayDSTOffset);

        // Calculate how many weeks ago that was
        long millisInThePast = System.currentTimeMillis() - parsedMillis;
        long weeksInThePast = millisInThePast / MILLISECONDS_PER_WEEK;
        // Add that number of weeks plus 1
        Date output = new Date(parsedMillis + (weeksInThePast + 1) * MILLISECONDS_PER_WEEK);

        System.out.println(input + " --> " + output);
    }
}

#2


1  

I wrote a conversion program. Here are the test results.

我写了一个转换程序。以下是测试结果。

Monday, 9:30 --> Mon May 23 09:30:00 MDT 2016
Friday, 16:45 --> Fri May 20 16:45:00 MDT 2016
Wednesday, 22:15 --> Wed May 18 22:15:00 MDT 2016

I assumed that the input time is 24 hour time. I'm in the mountain time zone (MDT). The date results will be in whichever time zone you run this code.

我假设输入时间是24小时。我在山区时区(MDT)。日期结果将在您运行此代码的任何时区。

I also assumed that if today's weekday is the same as the input weekday, I output today's date. Feel free to add code to check the current time to see if the appointment is today or next week. I considered that beyond the scope of the requirement.

我还假设如果今天的工作日与输入工作日相同,我输出今天的日期。随意添加代码以检查当前时间,以查看约会是今天还是下周。我认为超出了要求的范围。

Here's how I created the Date output.

这是我创建Date输出的方法。

  1. I split the input by ", ".

    我将输入分为“,”。

  2. I created a Calendar object with the current date and time.

    我创建了一个包含当前日期和时间的Calendar对象。

  3. I converted the weekday text to a weekday integer.

    我将工作日文本转换为工作日整数。

  4. I added the number of days necessary to get to the next weekday integer.

    我添加了到达下一个工作日整数所需的天数。

  5. I parsed the time part using the SimpleDateFormat, and copied the time to the Calendar object.

    我使用SimpleDateFormat解析时间部分,并将时间复制到Calendar对象。

Here's the code. This was not simple.

这是代码。这并不简单。

package com.ggl.testing;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DayTime {

    public static void main(String[] args) {
        getDate("Monday, 9:30");
        getDate("Friday, 16:45");
        getDate("Wednesday, 22:15");
    }

    private static void getDate(String input) {
        DayTime dayTime = new DayTime();
        Date output = dayTime.createDate(input);
        System.out.println(input + " --> " + output);
    }

    public Date createDate(String input) {
        String[] parts = input.split(", ");
        Calendar now = Calendar.getInstance();
        setDate(parts, now);
        setTime(parts[1], now);
        return now.getTime();
    }

    private void setDate(String[] parts, Calendar now) {
        int weekday;
        switch (parts[0]) {
        case "Sunday":
            weekday = Calendar.SUNDAY;
            break;
        case "Monday":
            weekday = Calendar.MONDAY;
            break;
        case "Tuesday":
            weekday = Calendar.TUESDAY;
            break;
        case "Wednesday":
            weekday = Calendar.WEDNESDAY;
            break;
        case "Thursday":
            weekday = Calendar.THURSDAY;
            break;
        case "Friday":
            weekday = Calendar.FRIDAY;
            break;
        default:
            weekday = Calendar.SATURDAY;
            break;
        }

        int currentWeekday = now.get(Calendar.DAY_OF_WEEK);

        if (weekday == currentWeekday) {
            return;
        }

        int difference = (weekday - currentWeekday + 7) % 7;
        now.add(Calendar.DAY_OF_MONTH, difference);
    }

    @SuppressWarnings("deprecation")
    private void setTime(String part, Calendar now) {
        Date date = getTime(part);
        if (date != null) {
            now.set(Calendar.HOUR_OF_DAY, date.getHours());
            now.set(Calendar.MINUTE, date.getMinutes());
            now.set(Calendar.SECOND, date.getSeconds());
        }
    }

    private Date getTime(String part) {
        SimpleDateFormat sdf = new SimpleDateFormat("H:mm");
        try {
            return sdf.parse(part);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

}

#1


2  

You can create a SimpleDateFormat matching your string. Then you'll use the .parse() method from that class to convert your String to a Date. See this question for a more detailed answer.

您可以创建与字符串匹配的SimpleDateFormat。然后,您将使用该类中的.parse()方法将String转换为Date。有关更详细的答案,请参阅此问题。

Alternately, you can create a Calendar object, and parse your string to set its appropriate fields and then use .getTime() to extract the Date.

或者,您可以创建一个Calendar对象,并解析您的字符串以设置其相应的字段,然后使用.getTime()来提取Date。

EDIT Inspired by Gilbert Le Blanc's answer, I produced his test case much more simply. The steps I used were:

编辑灵感来自Gilbert Le Blanc的回答,我更简单地制作了他的测试用例。我使用的步骤是:

  1. Use SimpleDateFormat to parse the given string including the date, producing a date in 1970.
  2. 使用SimpleDateFormat解析包含日期的给定字符串,在1970年生成日期。

  3. Adjust for any DST offsets
  4. 调整任何DST偏移

  5. Calculate how many weeks in the past the parsed date was.
  6. 计算解析日期过去的周数。

  7. Add this number of weeks to the past date in order to make it the next future date.
  8. 将此周数添加到过去的日期,以使其成为下一个未来日期。

Test output of my program matches Gilbert's (in my time zone):

我的节目的测试输出与吉尔伯特(在我的时区)匹配:

Monday, 9:30 --> Mon May 23 09:30:00 PDT 2016
Friday, 16:45 --> Fri May 20 16:45:00 PDT 2016
Wednesday, 22:15 --> Wed May 18 22:15:00 PDT 2016

You can tweak the approach based on what you really mean by "next". Here's my complete code:

您可以根据“下一步”的真正含义来调整方法。这是我的完整代码:

package foo.bar;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DayTime {

    public static final long MILLISECONDS_PER_WEEK = 7L * 24 * 60 * 60 * 1000;

    public static void main(String[] args) {
        getDate("Monday, 9:30");
        getDate("Friday, 16:45");
        getDate("Wednesday, 22:15");
    }

    private static void getDate(String input) {
        // Parse given date. Convert this to milliseconds since epoch. This will
        // result in a date during the first week of 1970.
        SimpleDateFormat sdf = new SimpleDateFormat("E, H:mm");
        Date date = sdf.parse(input, new ParsePosition(0));

        // Convert to millis and adjust for offset between today's Daylight
        // Saving Time (default for the sdf) and the 1970 date
        Calendar c = Calendar.getInstance();
        int todayDSTOffset = c.get(Calendar.DST_OFFSET);
        c.setTime(date);
        int epochDSTOffset = c.get(Calendar.DST_OFFSET);

        long parsedMillis = date.getTime() + (epochDSTOffset - todayDSTOffset);

        // Calculate how many weeks ago that was
        long millisInThePast = System.currentTimeMillis() - parsedMillis;
        long weeksInThePast = millisInThePast / MILLISECONDS_PER_WEEK;
        // Add that number of weeks plus 1
        Date output = new Date(parsedMillis + (weeksInThePast + 1) * MILLISECONDS_PER_WEEK);

        System.out.println(input + " --> " + output);
    }
}

#2


1  

I wrote a conversion program. Here are the test results.

我写了一个转换程序。以下是测试结果。

Monday, 9:30 --> Mon May 23 09:30:00 MDT 2016
Friday, 16:45 --> Fri May 20 16:45:00 MDT 2016
Wednesday, 22:15 --> Wed May 18 22:15:00 MDT 2016

I assumed that the input time is 24 hour time. I'm in the mountain time zone (MDT). The date results will be in whichever time zone you run this code.

我假设输入时间是24小时。我在山区时区(MDT)。日期结果将在您运行此代码的任何时区。

I also assumed that if today's weekday is the same as the input weekday, I output today's date. Feel free to add code to check the current time to see if the appointment is today or next week. I considered that beyond the scope of the requirement.

我还假设如果今天的工作日与输入工作日相同,我输出今天的日期。随意添加代码以检查当前时间,以查看约会是今天还是下周。我认为超出了要求的范围。

Here's how I created the Date output.

这是我创建Date输出的方法。

  1. I split the input by ", ".

    我将输入分为“,”。

  2. I created a Calendar object with the current date and time.

    我创建了一个包含当前日期和时间的Calendar对象。

  3. I converted the weekday text to a weekday integer.

    我将工作日文本转换为工作日整数。

  4. I added the number of days necessary to get to the next weekday integer.

    我添加了到达下一个工作日整数所需的天数。

  5. I parsed the time part using the SimpleDateFormat, and copied the time to the Calendar object.

    我使用SimpleDateFormat解析时间部分,并将时间复制到Calendar对象。

Here's the code. This was not simple.

这是代码。这并不简单。

package com.ggl.testing;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DayTime {

    public static void main(String[] args) {
        getDate("Monday, 9:30");
        getDate("Friday, 16:45");
        getDate("Wednesday, 22:15");
    }

    private static void getDate(String input) {
        DayTime dayTime = new DayTime();
        Date output = dayTime.createDate(input);
        System.out.println(input + " --> " + output);
    }

    public Date createDate(String input) {
        String[] parts = input.split(", ");
        Calendar now = Calendar.getInstance();
        setDate(parts, now);
        setTime(parts[1], now);
        return now.getTime();
    }

    private void setDate(String[] parts, Calendar now) {
        int weekday;
        switch (parts[0]) {
        case "Sunday":
            weekday = Calendar.SUNDAY;
            break;
        case "Monday":
            weekday = Calendar.MONDAY;
            break;
        case "Tuesday":
            weekday = Calendar.TUESDAY;
            break;
        case "Wednesday":
            weekday = Calendar.WEDNESDAY;
            break;
        case "Thursday":
            weekday = Calendar.THURSDAY;
            break;
        case "Friday":
            weekday = Calendar.FRIDAY;
            break;
        default:
            weekday = Calendar.SATURDAY;
            break;
        }

        int currentWeekday = now.get(Calendar.DAY_OF_WEEK);

        if (weekday == currentWeekday) {
            return;
        }

        int difference = (weekday - currentWeekday + 7) % 7;
        now.add(Calendar.DAY_OF_MONTH, difference);
    }

    @SuppressWarnings("deprecation")
    private void setTime(String part, Calendar now) {
        Date date = getTime(part);
        if (date != null) {
            now.set(Calendar.HOUR_OF_DAY, date.getHours());
            now.set(Calendar.MINUTE, date.getMinutes());
            now.set(Calendar.SECOND, date.getSeconds());
        }
    }

    private Date getTime(String part) {
        SimpleDateFormat sdf = new SimpleDateFormat("H:mm");
        try {
            return sdf.parse(part);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

}