Algorithm to convert UNIX Timestamp to 24hr format? [Solved]

I’m attempting to change the UNIX 10 figure timestamps the Dark Sky API provides into a readable 24hr clock format for sunset, sunrise and current time, but I’m struggling to find an algorithm for accomplishing this. Does anybody have a solution in jQuery?

Thanks!

I usually use moment.js

Add this to your codepen’s JS settings:
https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js

Then use it like this:

moment(unix_timestamp).format("dddd, MMMM Do YYYY, h:mm:ss a")

How to format.

1 Like

Thanks! Would it be best to use a function at the end of this line to incorporate moment.js into my code, or would I be manipulating the UNIX timestamp once the jQuery has already gathered it from the JSON and displayed it?

$("#theTime").hide().html(data.currently.time).fadeIn('slow');

I’m not sure what do you mean, but this should work:

$("#theTime").hide().html(moment(data.currently.time).format("dddd, MMMM Do YYYY, h:mm:ss a")).fadeIn('slow');

Although such a deep nesting is not very readable.

This would be cleaner:

var dateTime = moment(data.currently.time).format("dddd, MMMM Do YYYY, h:mm:ss a");
$("#theTime").hide().html(dateTime).fadeIn('slow');
1 Like

That seems to be working somewhat, but it’s showing what I believe is the UNIX Epoch, January 18th, 1970. I shall keep digging! We’re getting somewhere though.

EDIT: Got it working! Needed to add .unix after moment, like this:

$("#theTime").hide().html(moment.unix(data.currently.time).format("dddd, MMMM Do YYYY, h:mm:ss a")).fadeIn('slow');

Thanks for your help jenovs, moment is great to know about.