hey, I meet a problem when using this code ```val ...
# kotlinx-datetime
k
hey, I meet a problem when using this code
Copy code
val CURRENT_TIME_ZONE = TimeZone.currentSystemDefault()
fun now() = Clock.System.now().toLocalDateTime(CURRENT_TIME_ZONE).toInstant(TimeZone.UTC)
my timezone is asia/shanghai, and the test code is
Copy code
fun `test now instant`() {
        val nowInstant = now()
        println(nowInstant)
        println(CURRENT_TIME_ZONE)
    }
the result is
Copy code
2023-11-23T20:50:06.707128450Z
Asia/Shanghai
it is ok, but when using this
now
in the application, everything goes wrong how can I fix it ?
k
How is it wrong? The log produced at
04:00:00.006 UTC
shows a time (presumably produced by
now()
) of
04:00:00.003016035 UTC
. That looks right to me. The fact that your Windows task bar shows "8:45" means that you looked at the log 45 minutes later.
k
I have to tell you, the time in logger is not correct, the log shows 04:00 but the system time is "8:45pm" at the same time
k
I'm not sure why it's not working, but your code doesn't look correct. You seem to be mixing local times and instants. An Instant is an absolute, timezone-independent point in time. Any particular value of Instant represents the same point in time, occurring simultaneously, at all places on the planet. By defining
now()
as
Clock.System.now().toLocalDateTime(CURRENT_TIME_ZONE).toInstant(TimeZone.UTC)
, you seem to be using an Instant to present local time. If you want local time, use
LocalTime
(drop the
toInstant
from your function body).
k
but how can I use the
LocalTime
as
now()
, can you give me an example ?
by the way, there is also the problem about
@Schedule
, I have change the code into
Copy code
@Scheduled(cron = "0 0 4 * * *", zone = "Asia/Shanghai")
    fun refreshTasks() {
        <http://logger.info|logger.info>("refresh tasks at ${now()}")
        dailyAttendanceService.refreshDataDaily()
    }
so I can't set the zone as system default timezone, is there any way to fix it ?
k
fun now(): LocalDateTime = Clock.System.now().toLocalDateTime(CURRENT_TIME_ZONE)
Then your log message will show 000400 as the local time.
k
ok, thank you