我正在尝试创建一个程序来从字符串中解析有意义的日期和时间。我希望能够提供以下类型的输入,并创建一个日期/时间对象:
5 o'clock
5 p.m.
5 a.m.
5
530
530 a.m.
530 p.m.
Tuesday at [insert any above string here]
the 30th at [same as above]
May 12th at [same as above]
today at [same as above]
tomorrow at [same as above]
任何不包含日期/日期的字符串都可以假定为今天,任何没有 AM/PM 指定的时间都可以假定为发生在上午 9 点到晚上 8:59 之间。写完这段代码后,我很快意识到这变得多么混乱:
private void createEvent(String phrase) {
int hour;
int day = 0;
String dayOfWeek = "";
if (phrase.contains("o'clock")) {
hour = Integer.parseInt(phrase.substring(phrase.indexOf("o'clock")-3, phrase.indexOf("o'clock")-1).trim());
out.write(""+hour);
}
if (phrase.contains("tomorrow"))
day = (Calendar.DAY_OF_WEEK % 7)+1;
if (phrase.contains("sunday") || day == 1) {
dayOfWeek = "Sunday"; day = 1; }
else if (phrase.contains("monday") || day == 2) {
dayOfWeek = "Monday"; day = 2; }
else if (phrase.contains("tuesday") || day == 3) {
dayOfWeek = "Tuesday"; day = 3; }
else if (phrase.contains("wednesday") || day == 4) {
dayOfWeek = "Wednesday"; day = 4; }
else if (phrase.contains("thursday") || day == 5) {
dayOfWeek = "Thursday"; day = 5; }
else if (phrase.contains("friday") || day == 6) {
dayOfWeek = "Friday"; day = 6; }
else if (phrase.contains("saturday") || day == 7) {
dayOfWeek = "Saturday"; day = 7; }
else {
dayOfWeek = "Today"; day = 0; }
}
任何人都可以提供一些方向吗?