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

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

#1

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!


#2

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.


#3

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');

#4

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');

#5

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.