Modern date and time handling in all Android versions (without sugar)

栏目: IT技术 · 发布时间: 5年前

内容简介:Working with time in Android has always been tricky. People have been using either third party libraries (e.g.Joda-Time,In the latest Android Gradle plugin release (v.4.0.0+), "In general, Kotlin provides its Collections and Stream API replacements which a

Working with time in Android has always been tricky. People have been using either third party libraries (e.g.Joda-Time, ThreeTenBp ) or had to work with the built-in time classes (such asCalendar). The built-in classes, although available in all Android versions, had a not-so-great API, were mutable (so not thread-safe), and timezone handling was a pain ( ref ).

In the latest Android Gradle plugin release (v.4.0.0+), " Java 8+ API desugaring support " was introduced. In plain language, we can use some Java 8 APIs and the plugin will translate those APIs to Android-compatible Java behind the scenes that can be used in all Android versions without requiring a minimum API level!

In general, Kotlin provides its Collections and Stream API replacements which are superior to Java's in my opinion. So from the list of Java 8 APIs , I think that only the excellent java.time API is interesting for a Kotlin developer. Finally, a nice date/time API that can be used in Android!

Note that this "desugaring" process might cost a few extra KB in your APK/AAB. But if that's not a deal-breaker for your case, you should consider using the newer APIs.

Set up

You would need to modify your build.gradle files. More details (and up-to-date version codes) in the official doc .

android {
  [...]

  defaultConfig {
    // Required when setting minSdkVersion to 20 or lower
    multiDexEnabled true
  }

  compileOptions {    
    // Flag to enable support for the new language APIs
    coreLibraryDesugaringEnabled true
    // Sets Java compatibility to Java 8
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
  
  [...]
}



dependencies {
  [...]
  
  coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.0.9'
  
  [...]
}

Meet the classes

The time API is quite comprehensive and the complete exploration of the API is outside of the scope of this post. But, I want to introduce what I believe the main classes you probably going to need most of the time.

Instant

Instant is a point in time. Can be considered equivalent to a timestamp, if you are familiar with that term.

LocalTime, LocalDate, LocalDateTime

Each class represents the time, date, date+time respectively, without a timezone. Most people when thinking about date/time think in these terms anyway.

ZoneOffset, ZoneId

These are used to work with timezones. You would need one of those to convert a Local* to an Instant .

ZonedDateTime

You probably guessed it. This is what you get when combine a LocalDateTime with a ZoneId . This can be converted to an Instant .

Playing with date and time

These APIs provide intuitive and consistent ways to manipulate date and time. Remember that all objects are immutable, so a new object is created every time that a manipulation takes place (which is a good thing). Some useful examples follow.

val someDate = LocalDate.of(2020, 7, 28)
val someDateTime = LocalDateTime.ofEpochSecond(1595363833)
val someInstant = Instant.parse("2007-12-03T10:15:30.00Z")
Multiple ways to initialize time objects.
val today: LocalDate = LocalDate.now()
val startOfDay: LocalDateTime = today.atStartOfDay()
Get the start date+time of a day defined by a LocalDate
val now: LocalDateTime = LocalDateTime.now()
val nowInLA: ZonedDateTime = now.atZone(ZoneId.of("America/Los_Angeles"))
Get what date+time is now in Los Angeles.
val instant: Instant = nowInLA.toInstant()
val timestampInSeconds: Long = instant.epochSecond
val timestampInMilliseconds: Long = instant.toEpochMilli()
Get a point in time in various forms.
val today: LocalDate = LocalDate.now()
val previousWeek: LocalDate = LocalDate.now().minusWeeks(1)
Get the same day, 1 week earlier. There are available methods for every time unit.

Formatting

Just note that the formatters you are used to in Android, such as SimpleDateFormat , cannot be used with Java Time API. The API comes with its own formatters, such as DateTimeFormatter .

DateTimeFormatter.ISO_DATE.format(instant)

Enjoy a modern date/time API in your Android development life :)


很遗憾的说,推酷将在这个月底关闭。人生海海,几度秋凉,感谢那些有你的时光。


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

删除

删除

[英] 维克托•迈尔-舍恩伯格(Viktor Mayer-Schönberger)著 / 袁杰 译 / 浙江人民出版社 / 2013-1 / 49.90元

《删除》讲述了遗忘的美德,为读者展现了大数据时代的取舍之道。 《删除》从大数据时代信息取舍的目的和方法分别诠释了“被遗忘的权利”。维克托首先回溯了人类追寻记忆的过程,之后提出数字技术与全球网络正在瓦解我们天生的遗忘能力。对此,他考察了促进遗忘终止4大驱动力——数字化,廉价的存储器,易于提取,全球性访问。之后,他提出了当前数字化记忆的两大威胁——信息权力与时间,并给出了应对威胁的6大对策——数......一起来看看 《删除》 这本书的介绍吧!

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具