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?
String currentDateAndTime = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new Date());
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());
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With