I want to get the Date in MM/DD/YY
format from a timestamp.
I have used the below method but it does not gives proper output
final Calen
TimeZone utc = TimeZone.getTimeZone("UTC"); // avoiding local time zone overhead
final Calendar cal = new GregorianCalendar(utc);
// always use GregorianCalendar explicitly if you don't want be suprised with
// Japanese Imperial Calendar or something
cal.setTimeInMillis(1306249409L*1000); // input need to be in miliseconds
Log.d("Date--",""+cal.get(Calendar.DAY_OF_MONTH));
Log.d("Month--",""+cal.get(Calendar.MONTH) + 1); // it starts from zero, add 1
Log.d("Year--",""+cal.get(Calendar.YEAR));
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy");
String s = formatter.format(date);
System.out.println(s);
Better Approach
Simply Use SimpleDateFormat
new SimpleDateFormat("MM/dd/yyyy").format(new Date(timeStampMillisInLong));
Mistake in your Approach
DAY_OF_MONTH
,MONTH
, .. etc are just constant int value used by Calendar
class
internally
You can get the date represented by cal
by cal.get(Calendar.DATE)
What's wrong:
Calendar.DAY_OF_MONTH
, Calendar.MONTH
etc are static constants used to access those particular fields. (They will remain constant, no matter what setTimeInMillis
you provide.)
How to solve it:
To get those particular fields you can use the .get(int field)-method, like this:
Log.d("Month--",""+cal.get(Calendar.MONTH));
As others have pointed out there are more convenient methods for formatting a date for logging. You could use for instance the SimpleDateFormat
, or, as I usually do when logging, a format-string and String.format(formatStr, Calendar.getInstance())
.
Use the SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
String time = sdf.format(date);
Java uses the number of milliseconds since 1st January 1970 to represent times. If you compute the time represented by 1306249409 milliseconds, you'll discover that it's only 362 days, so your assumptions are wrong.
Moreover, cal.DAY_OF_MONTH
holds a constant. Use cal.get(Calendar.DAY_OF_MONTH)
to get the day of month (same for other parts of the date).