Hey I am using calendar instance to get current date and time.
private fun getCurrentCalendar() { Calendar.getInstance() }
Output:- Wed Jul 20 21:45:52 GMT 01:00 2022
If I want to reset time I need to use this function
fun resetCalendarTime(calendar: Calendar) {
calendar.set(Calendar.HOUR_OF_DAY, 0)
calendar.set(Calendar.MINUTE, 0)
calendar.set(Calendar.SECOND, 0)
calendar.set(Calendar.MILLISECOND, 0)
}
it will give this
Wed Jul 20 00:00:00 GMT 01:00 2022
My question is there any efficient way of doing that or this is fine in android?
CodePudding user response:
Caveat: Java syntax shown here, as I have not yet learned Kotlin.
tl;dr
LocalDate.now( zoneId ).atStartOfDay( zoneId )
Details
The terrible java.util.Calendar
class was years ago supplanted by the modern java.time classes defined in JSR 310. Never use either Date
class, Calendar
, SimpleDateFormat
, or any other legacy date-time class found outside the java.time
package.
On JVM
If you are running Kotlin on a JVM, use java.time classes.
To get the current moment as seen in a particular time zone, use ZonedDateTime
.
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
If you want to use the JVM’s current default time zone:
ZoneId z = ZoneId.systemDefault() ;
Apparently you want the first moment of the day. Your Question makes the mistake of assuming that time is always 00:00. Actually, on some dates in some time zones, the first moment occurs at a different time such as 01:00.