Skip to content Skip to sidebar Skip to footer

Simpledateformat Android Not Formatting As Expected

I'm trying to use SimpleDateFormat for formatting a date represented by 3 ints. It looks like this: ... SimpleDateFormat sdfHour = new SimpleDateFormat('HH'); SimpleDateFormat sdf

Solution 1:

SimpleDateFormat.format expects a Date, not an int. The method you're using, which is the overloaded version that accepts a long, is actually expecting milliseconds from the epoch, not an hour a minute or a second as you're doing.

The right way of using it should be :

SimpleDateFormatsdfHour=newSimpleDateFormat("HH:mm:ss");
StringtimeString= sdfHour.format(newDate());

Using "new Date()" as in this example, will give you the current time. If you need to format some other time (like one hour ago, or something from a database etc..) pass to "format" the right Date instance.

If you need the separated, for some reason, then you can still use it, but this other way :

SimpleDateFormatsdfHour=newSimpleDateFormat("HH");
SimpleDateFormatsdfMinute=newSimpleDateFormat("mm");
SimpleDateFormatsdfSecond=newSimpleDateFormat("ss");

Datenow=newDate();

Stringstring_hours= sdfHour.format(now);
Stringstring_minutes= sdfMinute.format(now);
Stringstring_seconds= sdfSecond.format(now);

Solution 2:

Try something like this:

Calendarcal= Calendar.getInstance();
SimpleDateFormatsdf=newSimpleDateFormat("HH:mm:ss");
StringCurrentTime= sdf.format(cal.getTime());

Solution 3:

You are calling wrong format method. You should supply a Date argument to a proper one, instead you are using this one, inherited from Format class:

publicfinalString format(Object obj)

Why does it work? Because of auto-boxing procedure in Java. You provide an int, it's automatically boxed to Integer which is a successor of Object

Solution 4:

You can't use SimpleDateFormat like this:

SimpleDateFormatsdfHour=newSimpleDateFormat("HH");
SimpleDateFormatsdfMinute=newSimpleDateFormat("mm");
SimpleDateFormatsdfSecond=newSimpleDateFormat("ss");

Use this:

longtimeInMillis= System.currentTimeMillis();
Calendarcal1= Calendar.getInstance();
cal1.setTimeInMillis(timeInMillis);
SimpleDateFormatdateFormat=newSimpleDateFormat("HH:mm:ss");
Stringdateformatted= dateFormat.format(cal1.getTime());

refer this

Post a Comment for "Simpledateformat Android Not Formatting As Expected"