Date manipulation in Android without a library

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

内容简介:I think that manipulating dates in an Android app is a quite common use case. If your app has anything to do with date/time, at some point you will need to do calculations with dates. For example, you might need to calculate the dates that define "last wee

I think that manipulating dates in an Android app is a quite common use case. If your app has anything to do with date/time, at some point you will need to do calculations with dates. For example, you might need to calculate the dates that define "last week" or "this week".

Now, there are some quite powerful libraries out there that can handle and manipulate dates and times quite well (e.g. Joda-Time ). But what if you want to make some basic date/time manipulation without using a library?

Calendar

Android got you covered. The good news is that there's a class called Calendar , that is available since API level 1 (not every class methods is, but most of them are). No compat libraries, no if API statements, built-in the OS since the beginning. The bad news is that the API is kind of ugly but Kotlin makes it bearable.

Initialization

You can initialize a Calendar instance at a specific point in time using 2 ways.

val calendar = Calendar.getInstance().apply { // [1]
    add(Calendar.DAY_OF_MONTH, 16)
    add(Calendar.MONTH, 6) // [2]
    add(Calendar.YEAR, 2020)
    set(Calendar.HOUR_OF_DAY, 21)
    set(Calendar.MINUTE, 48)
    set(Calendar.SECOND, 47)
    set(Calendar.MILLISECOND, 0)
}
1. Set each time filed separately
val calendar = Calendar.getInstance().apply { 
    time = 1594936127000 // [3] Thursday, July 16, 2020 9:48:47 PM
}
2. By setting the epoch milliseconds
  1. apply is ascoped function used to manipulate the Calendar instance  returned by the getInstance() method.
  2. The month is zero-index. So January = 0 .... December = 11.
  3. Just in case, the definition of "epoch":

The Unix epoch (or Unix time or POSIX time or Unix timestamp) is the number of seconds that have elapsed since January 1, 1970.

Check epochconverter for some useful tools when working with this kind of timestamp.

Manipulating date and time

Once you get an instance of Calendar pointing to a specific point in time, it's easy to manipulate date and time. Note that if we do not explicitly set a time in the Calendar instance, like shown before, then the current time is set by default.

Start of a time period

You can selectively change the time fields you need. For instance, to get the first day of the current month:

val startOfMonth = Calendar.getInstance().apply {
    set(Calendar.DAY_OF_MONTH, 1)
    set(Calendar.HOUR_OF_DAY, 0)
    set(Calendar.MINUTE, 0)
    set(Calendar.SECOND, 0)
}

You can do the same for getting the beginning of the current week:

val startOfWeek = Calendar.getInstance().apply {
    firstDayOfWeek = Calendar.MONDAY
    set(Calendar.DAY_OF_WEEK, it.firstDayOfWeek)
    set(Calendar.HOUR_OF_DAY, 0)
    set(Calendar.MINUTE, 0)
    set(Calendar.SECOND, 0)
    set(Calendar.MILLISECOND, 0)
}

Here we are defining the first day of the week to be Monday. Then we are setting the current time of the calendar to the last Monday.

Notice that we are using the field setters to set the time to the beginning of the day. This is because the time was set to the current time when the getInstance() was called. So, except if you call this on midnight, you would want to take care of hours, minutes, etc.

Add/remove time periods

Similarly to setting specific time fields, you can add or subtract time periods after getting a Calendar instance. For instance, for getting the beginning of the previous month:

val startOfPreviousMonth = Calendar.getInstance().apply {
    time = startOfMonth.time
    add(Calendar.MONTH, -1)
}

Here we are initially setting the time at the beginning of this month (from the last section). Then we are subtracting a month. You can do this for days, months, hours, etc.

Converting to other date/time representations

At any time you can convert the Calendar instance to Date or epoch milliseconds by calling the time or timeInMillis properties respectively.

startOfPreviousMonth.time // for getting a Date()
startOfPreviousMonth.timeInMillis // for getting a Long (epoch milliseconds)

Happy date and time manipulations :)


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

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

算法笔记

算法笔记

胡凡、曾磊 / 机械工业出版社 / 2016-7 / 65

这是一本零基础就能读懂的算法书籍,读者不需要因为自己没有语言基础而畏惧。书籍的第2章便是一个C语言的入门教程,内容非常易懂,并且十分实用,阅读完这章就可以对本书需要的C语言基础有一个较好的掌握。 本书已经覆盖了大部分基础经典算法,不仅可以作为考研机试和PAT的学习教材,对其他的一些算法考试(例如CCF的CSP考试)或者考研初试的数据结构科目的学习和理解也很有帮助,甚至仅仅想学习经典算法的读者......一起来看看 《算法笔记》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具