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.
CodePudding user response:
Change ZoneId.systemDefault()
to UTC TimeZone
val timestamp = startOfDay.atZone(ZoneId.of("UTC")).toInstant().epochSecond
CodePudding user response:
tl;dr
LocalDate.now( z ).atStartOfDay( z ).toInstant().getEpochSecond() ;
Details
I am not sure what is going wrong in your code, but it seems to be a matter of time zone.
Another problem is that you rely implicitly on the JVM’s current default time zone. Any code in any thread of any app can change that default at any moment. So, better to specify your desired or expected time zone. Or at least capture the default once and reuse, rather than accessing the current default multiple times.
And your code is overwrought, jumping through unnecessary hoops.
In Java syntax:
ZoneId z = ZoneId.systemDefault() ; // Or specify: ZoneId.of( "Asia/Kolkata" ) ;
LocalDate today = LocalDate.now( z ) ;
ZonedDateTime startOfToday = today.atStartOfDay( z ) ;
Instant instant = startOfToday.toInstant() ;
long countOfSecondsSinceEpochReference = instant.getEpochSecond() ;
See also my Answer to a similar Question.