例如,當前 UTC 時間是:
2021 年 11 月 5 日星期五 17:14:24 UTC
我想得到結果“6”(星期日 = 1 => 星期五 = 6)
uj5u.com熱心網友回復:
使用kotlinx.datetime(多平臺):
import kotlinx.datetime.DayOfWeek
import kotlinx.datetime.Instant
import kotlinx.datetime.TimeZone
import kotlinx.datetime.isoDayNumber
import kotlinx.datetime.toLocalDateTime
public val DayOfWeek.dayNumberStartingFromSunday: Int
get() = when (this) {
DayOfWeek.SUNDAY -> 1
else -> isoDayNumber 1
}
fun main() {
// val now: Instant = Clock.System.now()
val now = Instant.parse("2021-11-05T17:14:24Z")
val datetimeInUtc = now.toLocalDateTime(TimeZone.UTC)
val dayNumberStartingFromSunday = datetimeInUtc.dayOfWeek.dayNumberStartingFromSunday
println(dayNumberStartingFromSunday) // 6
}
uj5u.com熱心網友回復:
一周的第一天是Locale特定的。由于您想要一周的第一天,因此Sunday可以使用Locale.US.
演示:
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.time.temporal.WeekFields;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Test
System.out.println(getDayOfWeekValue(LocalDateTime.of(2021, 11, 5, 17, 14, 24)));
}
static int getDayOfWeekValue(LocalDateTime input) {
return Math.toIntExact(
ChronoUnit.DAYS.between(
input.with(
TemporalAdjusters.previousOrSame(
WeekFields.of(Locale.US)
.getFirstDayOfWeek())),
input.plusDays(1)));
// Note: One day has been added as ChronoUnit.DAYS.between excludes
// the second parameter while calculating the number of days
}
}
輸出:
6
ONLINE DEMO
注意:使用Locale.UK(一周的第一天是星期一)測驗此代碼,您將獲得 5 作為輸出。根據您的要求,您可以更改函式的定義,例如
static int getDayOfWeekValue(LocalDateTime input, Locale locale) {
return Math.toIntExact(
ChronoUnit.DAYS.between(
input.with(
TemporalAdjusters.previousOrSame(
WeekFields.of(locale)
.getFirstDayOfWeek())),
input.plusDays(1)));
// Note: One day has been added as ChronoUnit.DAYS.between excludes
// the second parameter while calculating the number of days
}
從Trail: Date Time 中了解有關現代日期時間 API * 的更多資訊。
* 如果您正在為 Android 專案作業并且您的 Android API 級別仍然不符合 Java-8,請檢查通過 desugaring 可用的 Java 8 API。請注意,Android 8.0 Oreo 已提供對java.time. 檢查此答案和此答案以了解如何將java.timeAPI 與 JDBC結合使用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/356608.html
標籤:科特林 约会时间 世界标准时间 星期几 格林威治标准时间
