Simpledateformat Gethours() Return Incorrect Value
Why getHours() for '09:50' return 8? Code: SimpleDateFormat sdf = new SimpleDateFormat('HH:mm'); Date date = sdf.parse('09:50'); int hours = date.getHours(); // return 8 instead of
Solution 1:
Calendar prueba = Calendar.getInstance();
prueba.set(2013, 1, 6, 10, 49, 32);
int day = prueba.get(Calendar.DAY_OF_MONTH);
int month = prueba.get(Calendar.MONTH);
int year = prueba.get(Calendar.YEAR);
int hours = prueba.get(Calendar.HOUR);
int minutes = prueba.get(Calendar.MINUTE);
int seconds = prueba.get(Calendar.SECOND);
Log.v("printf", "Date: " + day + "/"
+ month + "/"
+ year + "\n");
Log.v("printf", "Time: " + hours + ":"
+ minutes + ":"
+ seconds + "\n");
PD: Remember field Month from Calendar class begin by 0 (0-January, 1-February, ...) PD2: I have personalize tag on filter logcat called "printf". Change that for your tag that you use.
Solution 2:
It seems your SimpleDateFormat may not have been set to the default time zone. Calling:
sdf.setTimeZone(TimeZone.getDefault());
before parsing the literal should solve your problem. I have tested the following code:
...
public static final SimpleDateFormat CDfTimestamp = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
...
Date da1 = null;
for (String dl1 : new String[] { "1970-01-01 12:34:56",
"2016-01-01 12:34:56" }) {
try {
CDfTimestamp.setTimeZone(TimeZone.getTimeZone("GMT+05:00"));
da1 = CDfTimestamp.parse(dl1);
System.out.printf("parse GMT+05:00 %s -> %d %d %d (os=%d)\n", dl1, da1
.getHours(), da1.getMinutes(), da1.getSeconds(), CDfTimestamp
.getTimeZone().getOffset(0));
CDfTimestamp.setTimeZone(TimeZone.getTimeZone("UTC"));
da1 = CDfTimestamp.parse(dl1);
System.out.printf("parse UTC %s -> %d %d %d (os=%d)\n", dl1, da1
.getHours(), da1.getMinutes(), da1.getSeconds(), CDfTimestamp
.getTimeZone().getOffset(0));
CDfTimestamp.setTimeZone(TimeZone.getDefault());
da1 = CDfTimestamp.parse(dl1);
System.out.printf("parse default %s -> %d %d %d (os=%d)\n", dl1, da1
.getHours(), da1.getMinutes(), da1.getSeconds(), CDfTimestamp
.getTimeZone().getOffset(0));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
...
obtaining the following output:
parse GMT+05:001970-01-0112:34:56 -> 83456 (os=18000000)
parse UTC 1970-01-0112:34:56 -> 133456 (os=0)
parse default 1970-01-0112:34:56 -> 123456 (os=3600000)
parse GMT+05:002016-01-0112:34:56 -> 83456 (os=18000000)
parse UTC 2016-01-0112:34:56 -> 133456 (os=0)
parse default 2016-01-0112:34:56 -> 123456 (os=3600000)
Solution 3:
Date is deprecated. you should use calendar.
SimpleDateFormatsdf=newSimpleDateFormat("HH:mm");
Datedate= sdf.parse("09:50");
Calendarcal=newGregorianCalendar();
cal.setTime(date);
inthours= cal.get(Calendar.HOR_OF_DAY);
Post a Comment for "Simpledateformat Gethours() Return Incorrect Value"