Date and Time Formatting: Getting the current date in Android
Getting the date and time in Android is essential in many cases, especially if you want to log an action. To get the current date and time in android, you need to use the Calendar
function. You need to get an instance of the Calendar function and then you can access the time and date.
Calendar c = Calendar.getInstance(); Date date = c.getTime(); date.toString();
The getTime()
function returns an instance of Date
which is of the following format:
Fri Sep 16 18:30:36 IST 2016
Date and time formats are specified by date and time pattern strings. This date and time can be designated by:
EEE MMM dd HH:mm:ss z yyyy
The table below shows what the pattern letters, date/time component and their designation with how they are presented:
Letter | Date or Time Component | Presentation | Examples |
---|---|---|---|
E | Day name in week | Text | Friday; Fri |
M | Month in year | Month | September; Sep; 09 |
d | Day in month | Number | 16 |
H | Hour in day (0-23) | Number | 18 |
m | Minute in hour | Number | 30 |
s | Second in minute | Number | 36 |
z | Time zone | General time zone | Indian Standard Time; IST; GMT+5:30 |
|
Year | Year | 2016; 16 |
Formatting the Date
The above function returns the date in a preset pattern. To get the date in a custom pattern you can use:
DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy, HH:mm"); String date = df.format(Calendar.getInstance().getTime());
This outputs something like:
Wed, 4 Jul 2001 12:08
You can have DateFormat patterns like these:
"yyyy.MM.dd G 'at' HH:mm:ss z" ---- 2001.07.04 AD at 12:08:56 IST "hh 'o''clock' a, zzzz" ----------- 12 o'clock PM, Indian Standard Time "EEE, d MMM yyyy HH:mm:ss Z"------- Wed, 4 Jul 2001 12:08:56 +0530 "yyyy-MM-dd'T'HH:mm:ss.SSSZ"------- 2001-07-04T12:08:56.235+0530 "yyMMddHHmmssZ"-------------------- 010704120856+0530 "K:mm a, z" ----------------------- 0:08 PM, IST "h:mm a" -------------------------- 12:08 PM "EEE, MMM d, ''yy" ---------------- Wed, Jul 4, '01
Alternative Method:
To get the current date in Android, we can also use DateFormat
along with getDateInstance()
function.
Date date = new Date(); DateFormat.getDateInstance().format(date);
This outputs the date as:
Sep 16, 2016
You can also use the following functions:
DateFormat.getDateTimeInstance() ----- Sep 16, 2016 6:00:00 PM DateFormat.getTimeInstance() --------- 6:00:00 PM