gpt4 book ai didi

Java日历: Subtract two Dates to get difference in days between the two

转载 作者:行者123 更新时间:2023-12-02 13:25:10 26 4
gpt4 key购买 nike

我想检查我的用户登录以来已经有多少天了:

Calendar lastLogin = Calendar.getInstance();
lastLogin.setTime(randomPlayer.getLastLogin());
Calendar today = Calendar.getInstance();

如何减去这个值以获得两者之间的天数差异?即自上次登录以来的天数。

最佳答案

我建议使用LocalDate相反:

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

public class DaysBetween {

public static void main(String[] args) {
LocalDate lastLogin = LocalDate.of(2017, 4, 1);
LocalDate today = LocalDate.now();
System.out.println(daysBetween(lastLogin, today));
}

private static long daysBetween(LocalDate from, LocalDate to) {
return ChronoUnit.DAYS.between(from, to);
}
}

或者,如果您真的想坚持使用日历:

import java.time.temporal.ChronoUnit;
import java.util.Calendar;

public class DaysBetween {

public static void main(String[] args) {
Calendar lastLogin = Calendar.getInstance();
lastLogin.set(Calendar.YEAR, 2017);
lastLogin.set(Calendar.MONTH, 3);
lastLogin.set(Calendar.DAY_OF_MONTH, 1);
Calendar today = Calendar.getInstance();
System.out.println(daysBetween(lastLogin, today));
}

private static long daysBetween(Calendar from, Calendar to) {
return ChronoUnit.DAYS.between(from.toInstant(), to.toInstant());
}
}

关于Java日历: Subtract two Dates to get difference in days between the two,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43411808/

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