gpt4 book ai didi

java - 测试键盘输入的字符串是否具有有效的日期和格式

转载 作者:行者123 更新时间:2023-11-29 04:03:32 29 4
gpt4 key购买 nike

我在尝试编写正确的代码来测试键盘字符串是否包含有效日期以及每个特定月份的天数和格式 mm/dd/yyyy 以及闰年调整时遇到问题是我到目前为止所做的我认为我什至不接近但任何帮助将不胜感激。提前致谢

/* read a date from a string from the keyboard to determine if date is in mm/dd/yyyy format.

*/
import java.util.Scanner;

public class DateFormat

{

public static void main(String [ ] args)

{

Scanner inp = new Scanner(System.in);

System.out.println("Enter the date in mm/dd/yyyy format. ");

int mm;

int dd;

int yy;

int date = inp.nextInt();

boolean isLeapYear;

if ((mm <1) && (mm >12))

System.out.println( date + " is not valid month must be between 1 and 12.");
if (( mm = 4) && ( dd <=30 ))
System.out.println( date + " is a valid date.");
}
else
System.out.println(date + " is not valid date must have 30 or less days. ");
if (date = mm + "/" + dd + "/" + yy);
System.out.println( date + " is a valid date format. ");
}
else{
System.out.println( date + " is not valid must be in dd/mm/yyyy format.");

if (yy %100 ==0) {
if (yy % 400 ==0){
isLeapYear = true;
}
else{
isLeapYear = false;
}
}
else{
if (yy %4 ==0){
isLeapYear = true;
}
else{
isLeapYear = false;

if (isLeapYear)
if ((mm ==2) && (dd <= 29 ))
System.out.println(date + " is a valid date.");
}
else{
System.out.println( date + "is not valid month must have 29 days or less.");
if ((mm ==2) && (dd<=28))
System.out.println( date + " is a valid date.");
}
else{
System.out.println( date + "is not valid must have 28 days or less. ");

最佳答案

我认为这会有所帮助: http://www.javadb.com/check-if-a-string-is-a-valid-date

基本上,您真的不需要编写代码来检查日期是否有效。例如,您可以使用 java.text 包中的 SimpleDataFormat 类。

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Valid? " + isValidDate(scanner.nextLine()));
}

private boolean isValidDate(String inDate) {

if (inDate == null)
return false;

//set the format to use as a constructor argument
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

if (inDate.trim().length() != dateFormat.toPattern().length())
return false;

dateFormat.setLenient(false);

try {
//parse the inDate parameter
dateFormat.parse(inDate.trim());
}
catch (ParseException pe) {
return false;
}
return true;
}

关于java - 测试键盘输入的字符串是否具有有效的日期和格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1812979/

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