Learn Date and Time in Android

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

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.

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.

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.

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!”.

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.

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.

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.

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.


  1. The steps to format date and/or time in Android are
  2. You get or generate the date that you want to display
  3. You call on DateFormat or any of its sub classes such as SimpleDateFormat to format the date or
  4. 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

mTodayDate = (TextView)findViewById(R.id.today_date);

        //Get or Generate Date
        Date todayDate = new Date();

        //Get an instance of the formatter
        DateFormat dateFormat = DateFormat.getDateTimeInstance();
        //If you want to show only the date then you will use
        //DateFormat dateFormat = DateFormat.getDateInstance();

        //Format date
        String todayDateTimeString = dateFormat.format(todayDate);

        //display Date

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

   Calendar cal = Calendar.getInstance();
        Date currentDate = cal.getTime();

        DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
        String formattedDateString = formatter.format(currentDate);

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

   private String getFormattedDate(long milliSeconds, String dateFormat)
        // Create a DateFormatter object for displaying date in specified format.
        DateFormat formatter = new SimpleDateFormat(dateFormat);

        // Create a calendar object that will convert the date and time value in milliseconds to date.
        Calendar calendar = Calendar.getInstance();
        return formatter.format(calendar.getTime());

And with that you can call the method like this

long dateFromDatabase = getExistingDateFromSomewhere();
String dateToDisplay = getFormattedDate(dateFromDatabase, "yyyy-MM-dd");

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:

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.

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:

  private String createProductTable = "CREATE TABLE ProductTable(" +
            "productname TEXT NOT NULL," +
            "datecreated BIGINT";

and with this SQL statement we can create an object of type Product with a long date field like this:

 Product temp = new Product();
        temp.productName = "Nice Product";
        temp.dateCreated = System.currentTimeMillis();

and here is how we will save that product object to database.

   private long saveDemo(Product product){

        SQLiteDatabase database = getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put("productname", product.getProductName());
        values.put("datecreated", product.getDateCreated());
        Long result = database.insert("ProductTable", null, values);
        return result;

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

   private long saveDemo(Product product){

        SQLiteDatabase database = getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put("productname", product.getProductName());
        values.put("datecreated", product.getDateCreated());
        Long result = database.insert("ProductTable", null, values);
        return result;

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

public class Person{
        private int id;
        private String name;
        private long birthday;

    //Create a person instance
    Person person1 = new Person();
    person1.setname("John Doe");
    if (mBirthday != null){

    public GregorianCalendar mBirthday;

    private void showDatePickerDialog() {
        //fire up the logic show the date picker dialog
        DialogFragment datePickerFragment = new BirthDatePickerDialogFragment();
        datePickerFragment.setTargetFragment(BirthdayFragment.this, 0);
        datePickerFragment.show(getFragmentManager(), "datePicker");


    public static class BirthDatePickerDialogFragment extends DialogFragment
            implements DatePickerDialog.OnDateSetListener{

        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // Use the current date as the default date in the picker
            final Calendar c = Calendar.getInstance();
            int year = c.get(Calendar.YEAR);
            int month = c.get(Calendar.MONTH);
            int day = c.get(Calendar.DAY_OF_MONTH);

            // Create a new instance of DatePickerDialog and return it
            return new DatePickerDialog(getActivity(), this, year, month, day);
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            BirthDateFragment targetFragment = (BirthDateFragment)getTargetFragment();
            if (year < 0){
                targetFragment.mBirthday = null;
            } else {
                targetFragment.mBirthday = Calendar.getInstance();
                targetFragment.mBirthday.set(year, monthOfYear, dayOfMonth);



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


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: