gpt4 book ai didi

java - 在 Java 中与时间交互

转载 作者:行者123 更新时间:2023-11-30 09:16:51 25 4
gpt4 key购买 nike

如何在 Java 中随时间进行加减?例如,我正在编写一个程序,当您输入就寝时间时,它会加上 90 分钟(1 个 sleep 周期的长度)来告诉您理想的起床时间。

Scanner input;
input = new Scanner (System.in);

int wakeup0;
int wakeup1;
int wakeup2;
int wakeup3;
int wakeup4;
int wakeup5;

System.out.println("When will you be going to bed?");
int gotobed = Integer.parseInt(input.nextLine());
wakeup0 = gotobed + 90;
wakeup1 = wakeup0 + 90;
wakeup2 = wakeup1 + 90;
wakeup3 = wakeup2 + 90;
wakeup4 = wakeup3 + 90;
wakeup5 = wakeup4 + 90;

System.out.println("You should set your alarm for: "+wakeup0+" "+wakeup1+" "+wakeup2+" "+wakeup3+" "+wakeup4+" or "+wakeup5);

如何才能使 90 与 915 相加得到 1045 而不是 1095?

最佳答案

以毫秒为单位计算一切。乍一看这似乎很不方便,但数学原理非常简单。

输入就寝时间时,您需要决定用户将如何操作。会是小时和分钟吗?是否会有 AM/PM 或 24 小时制。您将考虑哪个时区。所有这些都是通过 Calendar 或 DateFormat 类完成的,它会为您提供一个包含指定时间的长值。

之后,添加时间偏移就很容易了。

SimpleDateFormat df = new SimpleDateFormat("HHmm");
long bedttime = df.parse(inputValue).getTime();
long wakeup1 = bedttime + (90 * 60 * 1000); //90 minutes in milliseconds.
long wakeup2 = wakeup1 + (90 * 60 * 1000); //90 minutes in milliseconds.
long wakeup3 = wakeup2 + (90 * 60 * 1000); //90 minutes in milliseconds.
long wakeup4 = wakeup3 + (90 * 60 * 1000); //90 minutes in milliseconds.
long wakeup5 = wakeup4 + (90 * 60 * 1000); //90 minutes in milliseconds.

System.out.println("The first wakeup time is "+df.format(new Date(wakeup1)));

每个 long 值都包含警报应该响起的时间。再次使用格式化程序生成该时间值的用户友好表示。

关于java - 在 Java 中与时间交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19261531/

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