Android Simple Date Format Gives Wrong Date & Time while fetching current date & time using calendar

1.7k views Asked by At
Calendar c = Calendar.getInstance();
SimpleDateFormat date = new SimpleDateFormat("MM/dd/yyyy");
String formattedDate = date.format(c.getTime());
SimpleDateFormat time24hrs = new SimpleDateFormat("HH:mm");
String intime= time24hrs.format(c.getTime());

The Above code is used for getting the current date and time, the problem is it works well but some times gives wrong current date & time especially it returns previous date and time (wrong date & time) out of 100% it gives 80% correct date and time and 20% gives wrong date and time. I don't what is the bug or problem or misconception in the code. Please Help me to fix this problem. Thanks in Advance.

2

There are 2 answers

1
sayan On

Try this out:

DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy, HH:mm");
String date = df.format(Calendar.getInstance().getTime());

Where you can have DateFormat patterns such as:

"yyyy.MM.dd G 'at' HH:mm:ss z" ---- 2001.07.04 AD at 12:08:56 PDT
"hh 'o''clock' a, zzzz" ----------- 12 o'clock PM, Pacific Daylight Time
"EEE, d MMM yyyy HH:mm:ss Z"------- Wed, 4 Jul 2001 12:08:56 -0700
"yyyy-MM-dd'T'HH:mm:ss.SSSZ"------- 2001-07-04T12:08:56.235-0700
"yyMMddHHmmssZ"-------------------- 010704120856-0700
"K:mm a, z" ----------------------- 0:08 PM, PDT
"h:mm a" -------------------------- 12:08 PM
"EEE, MMM d, ''yy" ---------------- Wed, Jul 4, '01
1
Bharatesh On

To get time in 24hrs use k

SimpleDateFormat time24hrs = new SimpleDateFormat("kk:mm");
String intime= time24hrs.format(c.getTime());

Please refer this for Date format symbol list Android Official Site - SimpleDateFormat