gpt4 book ai didi

Java 从 DateFormat 获取 int 数字并让用户输入

转载 作者:行者123 更新时间:2023-12-01 11:03:22 26 4
gpt4 key购买 nike

在我的代码中,我希望获得日期格式的各个数字,以便我可以将它们用作 int 值:

public static final String DATE_FORMAT = "dd.MM.yyyy";

public int age()
{
DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
Date date = new Date();

// How to convert to int?
int currentnDay = ?;
int currentMonth = ?;
int currentYear = ?;
}

如果可能的话,我还希望一些用户输入可以一次性定义日、月和年:

private Date dateOfPublication;

public void input()
{
Scanner scn = new Scanner( System.in );
System.out.print( "Please enter dateOfPublication: " );
// How to setup input for this?
}

我希望你能帮助我,以前我都是单独做的,但是代码相当大,我想如果我能这样做的话会更漂亮..

更新:好的,我现在正在这样输入:

    System.out.print( "Please enter dateOfPublication, use format of x.x.xxxx: " );
userInputDate = scn.next();

String[] ary = userInputDate.split("\\.");

publicationDay = Integer.parseInt(ary[0]);
publicationMonth = Integer.parseInt(ary[1]);
publicationYear = Integer.parseInt(ary[2]);

感谢您的帮助!

最佳答案

看看 Java 8 的新 Time API(或者 JodaTime 或 Calendar 如果你确实遇到困难的话)

LocalDate ld = LocalDate.parse("16.10.2015", DateTimeFormatter.ofPattern(DATE_FORMAT));
System.out.println(ld);
System.out.println(ld.getDayOfMonth());
System.out.println(ld.getMonth().getValue());
System.out.println(ld.getYear());

哪些输出

2015-10-16
16
10
2015

现在,您可以简单地要求用户以给定格式输入日期并尝试解析结果,如果解析失败,您可以重新提示它们

例如...

Scanner input = new Scanner(System.in);
LocalDate ld = null;
do {

System.out.print("Please enter date in " + DATE_FORMAT + " format: ");
String value = input.nextLine();

try {
ld = LocalDate.parse(value, DateTimeFormatter.ofPattern(DATE_FORMAT));
} catch (Exception e) {
System.err.println(value + " is not a valid date for the format of " + DATE_FORMAT);
}

} while (ld == null);

System.out.println(ld);
System.out.println(ld.getDayOfMonth());
System.out.println(ld.getMonth().getValue()); // Is probably 0 indexed
System.out.println(ld.getYear());

关于Java 从 DateFormat 获取 int 数字并让用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33160340/

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