I am trying to get the today's date and time using the following code,
SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy HH:mm");
String currentDateandTime = sdf.format(new Date());
but the outcome is
26/15/2014 13:15 instead of 26/1/2014 13:15
What is wrong?
Thanks!
Replace first mm with MM. Check documentation at http://developer.android.com/reference/java/text/SimpleDateFormat.html
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
String currentDateandTime = sdf.format(new Date());
replace dd/mm/yyyy
by dd/MM/yyyy
capital M for month
small m for minute
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
String currentDateandTime = sdf.format(new Date());
Your formatting is wrong "dd/mm/yyyy HH:mm"
it should be "dd/MM/yyyy HH:mm"
, Notice the MM
Instead of SimpleDateFormat
use DateFormat
Because SimpleDateFormat
is Depreciated though
android.text.format.DateFormat dateFormat= new android.text.format.DateFormat();
dateFormat.format("dd/MM/yyyy HH:mm", new java.util.Date());
You should use right format
H hours
m minutes
s seconds
S fractions of Second
a am/pm marker
d day of the month
M month of the year
y year
w week of year
String[] formats = new String[] {
"yyyy-MM-dd",
"yyyy-MM-dd HH:mm",
"yyyy-MM-dd HH:mmZ",
"yyyy-MM-dd HH:mm:ss.SSSZ",
"yyyy-MM-dd'T'HH:mm:ss.SSSZ",
};
for (String format : formats) {
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
System.out.format("%30s %s\n", format, sdf.format(new Date(0)));
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.format("%30s %s\n", format, sdf.format(new Date(0)));
}
and the output is
yyyy-MM-dd 1969-12-31
yyyy-MM-dd 1970-01-01
yyyy-MM-dd HH:mm 1969-12-31 16:00
yyyy-MM-dd HH:mm 1970-01-01 00:00
yyyy-MM-dd HH:mmZ 1969-12-31 16:00-0800
yyyy-MM-dd HH:mmZ 1970-01-01 00:00+0000
yyyy-MM-dd HH:mm:ss.SSSZ 1969-12-31 16:00:00.000-0800
yyyy-MM-dd HH:mm:ss.SSSZ 1970-01-01 00:00:00.000+0000
yyyy-MM-dd'T'HH:mm:ss.SSSZ 1969-12-31T16:00:00.000-0800
yyyy-MM-dd'T'HH:mm:ss.SSSZ 1970-01-01T00:00:00.000+0000
Which produces the above output when run in the America/Los_Angeles time zone:
know more from here
Use M instead of m for the month. m means minutes http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html