gpt4 book ai didi

Java——当用户输入日期字符串时显示一年中的某一天

转载 作者:行者123 更新时间:2023-12-01 17:19:30 27 4
gpt4 key购买 nike

因此,该程序将用户输入视为格式为“m/d/yyyy”或“mm/dd/yyyy”的字符串。然后它将月份显示为单词(例如,月份 1 变为“January”)。我需要做的最后一件事是使用 GregorianCalendar 类来确定日期在一年中的序数位置。我真的不知道该怎么做。任何帮助将不胜感激。

import javax.swing.*;
import java.text.*;
import java.util.*;

public class ConvertDate {

public static void main(String[] args) {


String date = "";
String[] monthName =
{"January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"};

Integer[] daysInMonth = {29, 30, 31};

int mm = 0;
int dd = 0;
int yy = 0;

String month = "";
String day = "";
String year = "";

int maxDay = 0;


while(mm < 1 || mm > 12 || dd < 1 || dd > maxDay) {


date = JOptionPane.showInputDialog(null, "Please, enter a date in the format MM/DD/YYYY.");

String[] partsOfTheDate = date.split("/");

mm = Integer.parseInt(partsOfTheDate[0]);
dd = Integer.parseInt(partsOfTheDate[1]);
yy = Integer.parseInt(partsOfTheDate[2]);

switch (mm) {
case 1: maxDay = daysInMonth[2]; // Jan
break;
case 2: maxDay = daysInMonth[0]; // Feb
break;
case 3: maxDay = daysInMonth[2]; // Mar
break;
case 4: maxDay = daysInMonth[1]; // Apr
break;
case 5: maxDay = daysInMonth[2]; // May
break;
case 6: maxDay = daysInMonth[1]; // Jun
break;
case 7: maxDay = daysInMonth[2]; // Jul
break;
case 8: maxDay = daysInMonth[2]; // Aug
break;
case 9: maxDay = daysInMonth[1]; // Sep
break;
case 10: maxDay = daysInMonth[2]; // Oct
break;
case 11: maxDay = daysInMonth[1]; // Nov
break;
case 12: maxDay = daysInMonth[2]; // Dec
break;
default: maxDay = 0;
break;
}

if((mm < 1 || mm > 12) || (dd < 1 || dd > maxDay)) {
System.out.println("You entered " + date + ";\nyou did not include a valid month, day, or both.");
}
else if((mm > 0 && mm < 13) && (dd > 0 && dd <= maxDay)) {
System.out.println("You entered " + date + ";\nthat can also be expressed as " + monthName[mm - 1] + " " + dd + ", " + yy + ".");
}

GregorianCalendar greg = new GregorianCalendar();
greg.setTime(date);
greg.get(greg.DAY_OF_YEAR);

}

}

}

最佳答案

使用SimpleDateFormatString解析为Date,然后将Date设置为Calendar > 并获取 day_of_year

<小时/>

相关

关于Java——当用户输入日期字符串时显示一年中的某一天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19748254/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com