【发布时间】:2020-09-07 12:52:58
【问题描述】:
我正在尝试编写一个基于 1 到 31(一个月中的一天)的数字的算法,它将返回该天/数字之前时刻的毫秒数。 该算法将始终使用今天的日期。
示例: 输入:5 输出:1601845199000,即 2020 年 10 月 4 日 23:59:59
=================
输入:31 输出:1601499599000,即 2020 年 9 月 30 日 23:59:59
因为该月没有 31 天,所以即使给出 31 天,算法也会采用最接近的日期。
2 月 29/30 日也是如此
val calendar = Calendar.getInstance()
calendar.set(Calendar.HOUR_OF_DAY, 23)
calendar.set(Calendar.MINUTE, 59)
calendar.set(Calendar.SECOND, 59)
calendar.clear(Calendar.MILLISECOND)
val lastDayNumber = 31
var found = false
while (!found) {
if (calendar.get(Calendar.DAY_OF_MONTH) <= lastDayNumber) {
found = true
}
if (calendar.get(Calendar.DAY_OF_MONTH) < lastDayNumber) {
calendar.add(Calendar.DATE, 1)
}
}
问题是calendar.add(Calendar.DATE, 1) 根本不工作。
这个方法应该找到未来给定数字的前一天。我错过了什么吗?我已经阅读了文档和其他 StackOverflow 答案,但我仍然无法得到它。
Edit1:我也尝试了calendar.add(Calendar.DAY_OF_MONTH, 1) 和 +1,但是,-1 工作得非常好。
编辑2:
看着GregorianCalendar.java我看到了以下内容:
// Handle week, day and AM_PM fields which involves
// time zone offset change adjustment. Convert the
// given amount to the number of days.
case WEEK_OF_YEAR:
case WEEK_OF_MONTH:
case DAY_OF_WEEK_IN_MONTH:
delta *= 7;
break;
case DAY_OF_MONTH: // synonym of DATE
case DAY_OF_YEAR:
case DAY_OF_WEEK:
break;
如果我以WEEL_OF_YEAR 为例,同样的代码也将在 week_of_month 和 day_of_week_in_month 运行,因为没有中断所有 3 个字段都通过相同的代码运行。
但是,我发现绝对没有代码可以在 DAY_OF_MONTH、DAY_OF_YEAR 和 DAY_OF_WEEK 上运行。
附:我找不到DATE 字段
================================================ ===
使用LocalDateTime
fun getLastDayOfMonth(date: LocalDateTime): Long {
val lastDayNumber = lastDay?.filter { it.isDigit() }!!.toInt()
var found = false
while (!found) {
if (date.dayOfMonth <= lastDayNumber) {
found = true
} else {
date.plusDays(1)
}
}
return date.toEpochSecond(ZoneOffset.UTC)
}
date.plusDays(1) is not changing the date variable to be next day ...
【问题讨论】:
-
您为什么要使用这个过时的日期时间 API?您不使用
java.time的任何具体原因?你到底想做什么?只是找到一个日期或日期?能不能解释的详细一点? -
什么是
lastDayNumber? -
没问题,但我还是没有得到你想要的?收到一个数字(它到底代表什么?)并找到前一天?我很乐意在这里提供帮助,但我没有得到输入,也没有想要的结果。请您为此添加示例吗?
-
@OleV.V.如果您输入 7 而今天是 9 月 7 日,您应该得到 10 月 6 日。如果你输入 8,你应该得到 9 月 7 日(今天)
-
感谢您提供所有信息以回答 cmets 中的问题。最好编辑问题并将其添加到那里,这样我们就可以将所有内容集中在一个地方。
标签: android date kotlin calendar