Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current time in android

Tags:

android

I want to get the current time in Android. It should be displayed like 2:30pm and I want to store it in a database. I searched a lot. But I don't know how to do it. How can I achieve this?

like image 812
Manikandan Avatar asked Aug 11 '12 09:08

Manikandan


4 Answers

String currentDateAndTime = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new Date());
like image 152
Jaydev Avatar answered Oct 06 '22 00:10

Jaydev


I get perfect time using below........

 String Time = java.text.DateFormat.**getTimeInstance()**.format(new Date()); 
 //and for to get date try it as below
 String date_L = java.text.DateFormat.**getDateInstance()**.format(new Date());
like image 22
Hiren Avatar answered Oct 05 '22 23:10

Hiren


Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+1:00"));
Date currentLocalTime = cal.getTime();
DateFormat date = new SimpleDateFormat("HH:mm a"); 
// you can get seconds by adding  "...:ss" to it
date.setTimeZone(TimeZone.getTimeZone("GMT+1:00")); 

String localTime = date.format(currentLocalTime); 
like image 33
Ahmad Avatar answered Oct 05 '22 23:10

Ahmad


To get the time in a 12 hour format try this code with "KK" instead of "HH". A full explanation of the symbols you can use are here.

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT-4:00"));
     Date currentLocalTime = cal.getTime();
     DateFormat date = new SimpleDateFormat("KK:mm");
     date.setTimeZone(TimeZone.getTimeZone("GMT-4:00")); 
     String localTime = date.format(currentLocalTime); 

Also to get the hour, minutes and seconds as integers you can use:

int currentHour = cal.get(Calendar.HOUR);
int currentMinutes = cal.get(Calendar.MINUTE);
int currentSeconds = cal.get(Calendar.SECOND);
like image 24
Raul Vazquez Avatar answered Oct 05 '22 23:10

Raul Vazquez