I want current time in millis and then to store it in 12 hour format but with this piece of code I am getting 24 hour format time.
long timeInMillis = System
Simply follow the code
public static String getFormatedDate(String strDate,StringsourceFormate,
String destinyFormate) {
SimpleDateFormat df;
df = new SimpleDateFormat(sourceFormate);
Date date = null;
try {
date = df.parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
}
df = new SimpleDateFormat(destinyFormate);
return df.format(date);
}
and pass the value into the function like that,
getFormatedDate("21:30:00", "HH:mm", "hh:mm aa");
or checkout this documentation SimpleDateFormat for StringsourceFormate and destinyFormate.
Change HH
to hh
as
long timeInMillis = System.currentTimeMillis();
Calendar cal1 = Calendar.getInstance();
cal1.setTimeInMillis(timeInMillis);
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd/MM/yyyy hh:mm:ss a");
dateforrow = dateFormat.format(cal1.getTime());
Note that dd/mm/yyyy
- will give you minutes instead of the month.
You can try it like this
Calendar c= Calendar.getInstance();
SimpleDateFormat sdf= new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
String str=sdf.format(c.getTime());
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss a");
use hh
in place of HH
I re-encounter this in the hard way as well. H vs h, for 24-hour vs 12 hour !
Referring to SimpleDataFormat JavaDoc:
Letter | Date or Time Component | Presentation | Examples
---------------------------------------------------------
H | Hour in day (0-23) | Number | 0
h | Hour in am/pm (1-12) | Number | 12