Search code examples
androidkotlindatetimetimestampunix-timestamp

How to get today's timestamp in GMT format - Kotlin


I am using below function to fetch the today's start Timestamp in kotlin- Android.

fun getTimeStampForStartOfTheDay(): String {
    val localDate = LocalDate.now()   // your current date time
    val startOfDay: LocalDateTime = localDate.atStartOfDay() // date time at start of the date
    val timestamp = startOfDay.atZone(ZoneId.systemDefault()).toInstant()
        .epochSecond // start time to timestamp
    return timestamp.toString()
}

The TimeStamp am getting is as : 1639593000

GMT: Wednesday, 15 December 2021 18:30:00

Your time zone: Thursday, 16 December 2021 00:00:00 GMT+05:30

Relative: 11 hours ago

But timestamp should be 1639612800

GMT: Thursday, 16 December 2021 00:00:00

Your time zone: Thursday, 16 December 2021 05:30:00 GMT+05:30

Relative: 5 hours ago

How can I achieve this ? Thanks.


Solution

  • Change ZoneId.systemDefault() to UTC TimeZone

     val timestamp = startOfDay.atZone(ZoneId.of("UTC")).toInstant().epochSecond