【发布时间】:2015-11-01 01:52:28
【问题描述】:
我正在创建一个日历实例,并将日期设置为 1997 年 7 月 1 日,如下所示:
int currentYear = Calendar.getInstance().get(Calendar.YEAR);
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(1997, 6, 1);
我想要做的是,在不使用外部库的情况下,在当前日期(例如 2015 年 11 月 1 日)之前从该日期获取以下输出(正确计算闰年/秒会很好,但不是必需的) 02:45:30):
18 年 4 个月 0 天 2 小时 45 分钟 30 秒
我不太确定这是否可能。我尝试了一些奇怪的、不太合乎逻辑的计算,需要大量改进,但无法使其工作:
int years = currentYear - calendar.get(Calendar.YEAR);
int months = calendar.get(Calendar.MONTH);
if(currentMonth > months) {
years -= 1;
}
更新 - 到目前为止的代码:
Calendar currentDate = Calendar.getInstance();
currentDate.clear();
Calendar birthDate = Calendar.getInstance();
birthDate.clear();
birthDate.set(this.birthYear, this.birthMonth - 1, this.birthDay);
Calendar date = Calendar.getInstance();
date.clear();
date.setTimeInMillis(birthDate.getTimeInMillis() - currentDate.getTimeInMillis());
System.out.println(Integer.toString(date.get(Calendar.YEAR)));
【问题讨论】:
-
将两个时刻转换为自纪元、UTC 以来的毫秒数,然后将差值(以毫秒为单位)转换为年、月、日等。
-
@MickMnemonic 没有正确理解。无论如何,我尝试将birthDate和currentDate都转换为millis,然后从birthDate中减去currentDate,得到... 1997。我做错了什么?
-
你能分享你所做的代码吗?您现在发布的内容不包括例如转换为毫秒。
-
你使用的是哪个版本的java?