Shares

Learn Date and Time in Android

Shares

Working with date and time is one of the common task Android developers perform. The framework provides a lot of tools and helper classes to help developers work with date and time in Android so we will start our tutorial by examining the common terms and concept that you will encounter when you work with Android DateTime.

Android Date and Time Basics

  1. Date – this refers to a point in time, for example the moment you are reading this blog post can be represented by a date. The values for a date mostly but not always come from System.currentTimeInMillis.
  2. DateTime – refers to two sides of the same moment – the date and time. You can refer to a person only by their first name (and this can be likened to a date) or you can refer to a person by their first and last name and this can be likened to Datetime. Both represents the same person.
  3. CurrentTimeInMillis – this refers to the number of seconds that have elapsed since UnixTime which is January 1, 1970. In Android this number is returned as a long primitive type.
  4. Calendar – when we say a moment in time, are we talking about the minute or the hour of the day, or the day of the month, or the month of the year and so fourth. Calendar is an abstract class that breaks down a Date instance down to integer representation of YEAR, MONTH, DAY, HOUR, etc. This way you can say if MONTH == MARCH AND DAY_OF_MONTH == 5 alert “Happy Birthday!”.
  5. GregoryCalender – this is subclass of the Calendar class that represents Calendar as we know it in the western world and some argue in the rest of the world. Unless you have a very strong reason not, you may want to use GregoryCalendar instead of the Calendar.
  6. DateFormat – you probably do not want to display date in your app as 521365987401202 which is the long value that the System.currentTimeInMillis may return. Instead you want to display date in human readable format. You use DateFormat and some of its static classes to format date and to parse string representation of dates back to date.
  7. SimpleDateFormat – apparently the versatile DateFormat needs some improvement and it got one called SimpleDateFormat which formats a date into locale-sensitive string representation of date. With this, the string representation of the second day of the month of June 2015 will be   June 2, 2015 or 6/2/2015 in the US, while in Europe the same will be represented as 2 June, 2015 or 2/6/2015.
  8. DateUtils – if you want to write code logic in Android to calculate how many minutes have elapsed from the time you went to sleep until when you woke up from sleep, the DateUtil will come to your rescue. It contains date related utilities to calculate elapsed time and date ranges.

Now that we have covered the basics of date time in Android, let us see how to put them to good use.

Formatting

The steps to format date and/or time in Android are

  1. You get or generate the date that you want to display
  2. You call on DateFormat or any of its sub classes such as SimpleDateFormat to format the date or
  3. You manually format the date either by String concatenation or other means

Here is an example of getting, formatting and displaying today’s current date and time

Of course there are many ways to obtain and display the current date and time such as this

What of if you already have an existing date that you want to format, say the date is coming from a field in the database or from an API call. To format and display the date, you first have to either obtain or convert the date to long and then you can create a method that accepts a long parameter and the format that you want the date to be displayed, here is an example

And  with that you can call the method like this

Saving DateTime in Android

Saving  date and time in Android is influenced by the persistence mechanism you are using and how you intend to use that date again and since SQLite database is the defacto persistence mechanism in Android here are some options to save date and time:

  1. String – you can simply save your datetime as String (Text in SQLite) if all you want to do with the date going forward is display it. Also you can use DateFormat to parse the saved String to date value and work with it later.
  2. Long – SQLite database and most database engines are not suitable for persisting non primitive objects like Java classes and since Date is a Java class you cannot save a field of type Date to a SQLite database. You can however convert your date to milliseconds and save to database. For example here is how you can create a fictitious product table and save it to database:
    and with this SQL statement we can create an object of type Product with a long date field like this:
    and here is how we will save that product object to database.
  3. SQLite Datetype – while SQLite does not have a storage class set aside for storing dates and/or times you can use SQLite built in datetime functions to work with date, with our fictitious product table can now be created like this
     

Android Date and Time Picker

The concept behind date and time pickers in Android is the same as in Web development – limiting user input to known formats. Using picker dialog saves you from writing parsing logic to parse every known format that your user may input date. Android provides ready to use dialogs that you can present to your users for them to use to select date and time that you can work with in your app. The challenge sometimes, is after the user select the date in the dialog how do you work with the date in your Activity or Fragment.

Here are some steps that you can use to work with date and time that your users select in the picker dialog.

  1. Create a Calendar or GregoryCalendar instance variable in your Activity or Fragment
  2. Create a Picker DialogFragment
  3. Set your Fragment as the target Fragment, so when then the user selects a date it will be delivered to your Fragment

For example if you have a Fragment called BirthDayFragment and you want to give your users a dialog to select their birthdays. When they select their birthday, you want to save that date in the database. Here is what you can do:

  1. Create a Person class with a property of type long to store the birthday as well as other properties you may need
  2. In the BirthdayFragment.java create a member variable of type Calendar that stores the date the user selected from the dialog picker
  3. Create a DialogFragment that implements DatePickerDialog and set your BirthdayFragment as the target Fragment
  4. When user selects a date from the dialog picker, store the date in the Calendar variable in your Fragment
  5. Convert the Calendar variable to long and save
  6. Here is a code demo to illustrate these steps
 

I hope that this blog post helps you with working with date and time and Android.

There are some problems with the configuration of the opt-in shortcode

Follow Me

About the Author valokafor

I am a Software Engineer with expertise in Android Development. I am available for Android development projects.

follow me on:

Leave a Comment: