Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript readable date/time from PHP's time()

Is it possible to have JavaScript compute a timestamp returned from PHP's time() function and present it in a readable format such as "Sun, 18th April 2010 at 4:00 pm"?

like image 820
Lyon Avatar asked Apr 17 '10 10:04

Lyon


2 Answers

Use the Date object to do that:

new Date(<?php echo time(); ?>*1000)

You need to multiply the Unix timestamp by 1000 becuase Date expects the timestamp to be in milliseconds.

And to format the date, you can use this Date.format method (Date has none built in).

like image 71
Gumbo Avatar answered Sep 29 '22 16:09

Gumbo


You're going to want to be really careful doing this stuff. When you take a server-side time value that's a traditional "number of seconds (or milliseconds) since the Epoch boundary" value, and then turn that into some sort of "Date" object, well a translation occurs into the time zone appropriate to the locale of the context.

The problem arises when you've got a server located in Chicago, and somebody in Hawaii using your site, say after a party — one of those "luau" affairs, no doubt, complete with roasted pig and grass-skirted dancing girls, a rare evening under warm tropical skies, exotic flowers scenting the ocean breezes — and it's late now. My goodness, it's almost midnight! Whatever will mother think when I write her about the party?

Our party-goer sits down at 11:30 PM to use your site. Now, of course, being considerably east of Hawaii, your server thinks it's 5:30AM, and the date is one day later than the date our party-goer will jot down in his quick note to Mom. So your server writes its time value into a web page as described in the answers here, and — correctly — the local Hawaii time shows up on the page in our party-goer's hotel room.

The problem is this: if that local time makes it back to your application from some form field, and your application treats it as local time in Chicago, then your site will get yesterday's date. Depending on your application that's either OK or it's not OK - the point is, you have to keep track of where a date (expressed in ordinary calendar notation) comes from vis-a-vis where the date is used.

You can of course have the opposite problem. That is, if your server always renders dates in its local time zone, then users elsewhere in the world will see confusing (apparently wrong) date and time values, so the interface has to make clear what those values mean. The issues become important when your site provides services involving schedules. If it's possible to schedule operations, it's important that the interface keeps things on the level so that "April 30th at 10:00PM" means either that date and time at the server or that date and time in the locale from which the schedule was arranged. Whichever it is, you have to be careful to keep things consistent.

like image 36
Pointy Avatar answered Sep 29 '22 14:09

Pointy