Converting seconds to date time String
I have seconds from epoch time and want to convert it to Day-Month-Year HH:MM
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(seconds*1000);
String dateString = calendar.get(Calendar.DAY_OF_WEEK) + ", "+.......
Above code is not working properly am i doing anything wrong here.
For example if seconds = 1299671538
then it generates time string as Friday, December 12, 1969
which is wrong it should display Wednesday, March 09, 2011
For example if seconds = 1299671538 then it generates time string as Friday, December 12, 1969 which is wrong it should display Wednesday, March 09, 2011
You have integer overflow. Just use the following (notice "L" after 1000 constant):
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(seconds*1000L);
String dateString = calendar.get(Calendar.DAY_OF_WEEK) + ", "+.......
or better use SimpleDateFormat class:
SimpleDateFormat formatter = new SimpleDateFormat("EEEE, MMMM d, yyyy HH:mm");
String dateString = formatter.format(new Date(seconds * 1000L));
this will give you the following date string for your original seconds input:
Wednesday, March 9, 2011 13:52
You need to use
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
instead of
Calendar cal = Calendar.getInstance();
because UTC time from seconds depends on Timezone.
You don't need a calendar in this case, you can simply use the constructor new Date(1000 * seconds)
Then use a SimpleDateFormat to create a String to display it.
For a full explanation on using SimpleDateFormat go here.
The answer to this question though is that you need to use long values instead of ints.
new Date(1299674566000l)
If you don't believe me, run this:
int secondsInt = 1299674566;
System.out.println(new Date(secondsInt *1000));
long secondsLong = 1299674566;
System.out.println(new Date(secondsLong *1000));
I can confirm that answer from @Idolon is working fine, simple snippet is below...
long created = 1300563523;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.US);
String dateString = formatter.format(new Date(created * 1000L));
using SimpleDateFormat is better way, change the format as you need.
Won't it work wihtout Calendar, like below? Haven't run this piece of code, but guess it should work .
CharSequence theDate = DateFormat.format("Day-Month-Year HH:MM", objDate);
精彩评论