I have seconds from epoch time and want to convert it to Day-Month-Year HH:MM
I have tried following but it gives me wrong value.
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
All you need to do is to divide the seconds value by 86400 to convert seconds into 1-day base.
To convert seconds to HH:MM:SS :Multiply the seconds by 1000 to get milliseconds. Pass the milliseconds to the Date() constructor. Use the toISOString() method on the Date object. Get the hh:mm:ss portion of the string.
Use the timedelta() constructor and pass the seconds value to it using the seconds argument. The timedelta constructor creates the timedelta object, representing time in days, hours, minutes, and seconds ( days, hh:mm:ss.ms ) format.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With