Date and Time Formatting in Android
Date and Time in Android are formatted using the SimpleDateFormat library from Java, using Calendar instance which helps to get the current system date and time. The current date and time are of the type Long which can be converted to a human-readable date and time. In this article, it’s been discussed how the Date and Time values can be formatted in various formats and displayed. Have a look at the following image to get an idea of the entire discussion.
Steps to Format the Date and Time in Android
Step 1: Create an empty activity project
- Using Android Studio create an empty activity project. Refer to Android | How to Create/Start a New Project in Android Studio?
Step 2: Working with the activity_main.xml file
- The main layout of the activity file containing 8 TextViews. One to show the current system date and time value in Long type, and others to display the same date and time value in a formatted human-readable way.
- To implement the UI invoke the following code inside the activity_main.xml file.
Step 3: Working with the MainActivity file
Understanding the way of formatting the date and time in Android using SimpleDateFormat
- Firstly, the instance of the Calendar is created and the desired format of the date and time to be shown is passed to the SimpleDateFormat method. The String should include the following characters and one may include the separators like -, / etc.
- The below table includes the characters to be used to generate the most used common pattern of date and time.
Character to be used
|dd||Date in numeric value|
|E||Day in String (short form. Ex: Mon)|
|EEEE||Day in String (full form. Ex: Monday)|
|MM||Month in numeric value|
|yyyy||Year in numeric value|
|LLL||Month in String (short form. Ex: Mar)|
|LLLL||Month in String (full form. Ex: March)|
|HH||Hour in numeric value (24hrs timing format)|
|KK||Hour in numeric value (12hrs timing format)|
|mm||Minute in numeric value|
|ss||Seconds in numeric value|
|aaa||Displays AM or PM (according to 12hrs timing format)|
|z||Displays the time zone of the region|
- Refer to the following code and its output to get a better idea of the above table.