-1

I want to show current time of device in app. following is the code is getting time but problem is if current time is 12:15 but my variable cTime has opposite time that is 00:15. Below is my code for getting time, please help me out

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
Calendar c = Calendar.getInstance();
int currentHour = c.get(Calendar.HOUR);
int currentMin = c.get(Calendar.MINUTE);
String currentTime = currentHour+":"+currentMin;
Date cTime = sdf.parse(currentTime);
Vickyexpert
  • 3,147
  • 5
  • 21
  • 34
Imran
  • 39
  • 9

4 Answers4

1

You should use Calendar.HOUR_OF_DAY instead of Calendar.HOUR to get the hour in 0-24 format.

Egor
  • 39,695
  • 10
  • 113
  • 130
0

Try this Code For current time

Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("h:mm aa");
String datetime = sdf.format(now);
Arjun saini
  • 4,223
  • 3
  • 23
  • 51
0

Use this simple method for get device current time in milisecound

System.currentTimeMillis();
Nitesh Pareek
  • 362
  • 2
  • 10
0

Always, always read the documentation for the code you're using.

You are formatting your hours with the H pattern, which describes the 24 hour model:

H | Hour in day | (0-23) | Number | 0

You need to use the small h, which represents the “Hour in am/pm (1-12)”:

SimpleDateFormat format = new SimpleDateFormat("hh:mm");
Date date = new Date();
String dateReadable = format.format(date);
// Use your String elsewhere.

And this is all you need to get started. No need to create ints and Calendars for this. You can also put the a for the period indicator, as Arjun said below.

This is the foundation for this answer, too, but considering the code is slightly different and you are facing difficulties (by looking at your code), I didn't consider it a duplicate.

Community
  • 1
  • 1
davidcesarino
  • 16,160
  • 16
  • 68
  • 109
  • sir format is not my problem, actually my problem is getting current hour and current minute of my mobile. current minute is ok but problem is in hour. if the cell phone current time is 11:00 of morning but above code returns 23:00 means 11 of night. can u help me with that? – Imran Jul 13 '16 at 07:22
  • @Imran I seriously doubt that the system shows 11:00 AM to the user while the code above returns 23:00. Your phone hour is probably badly configured... it can be the hour itself or the time zone chosen. Please check the Time And Date settings in your phone. – davidcesarino Jul 16 '16 at 01:30