开发者

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

开发者 https://www.devze.com 2022-12-27 10:20 出处:网络
Is it possible to have JavaScript compute a timestamp returned from PHP\'s time() funct开发者_运维问答ion and present it in a readable format such as \"Sun, 18th April 2010 at 4:00 pm\"?Use the Date o

Is it possible to have JavaScript compute a timestamp returned from PHP's time() funct开发者_运维问答ion and present it in a readable format such as "Sun, 18th April 2010 at 4:00 pm"?


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).


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.


Instead of a numeric unix timestamp you can also send a textual representation of the date that Date.parse() understands.
Maybe it's just my contribution to global warming but I think there are benefits in using a format that is a bit more human readable and contains the timezone info.

e.g.

<?php
// I have "decided" America/Los_Angeles fits most of my audience
date_default_timezone_set('America/Los_Angeles');
$now = time();
$yesterday = strtotime('yesterday', $now);
// March 27, 1976 08:00:00 tz:America/Los_Angeles
$someotherdate = mktime(8, 0, 0, 3, 27, 1976)
?><html>
  <head><title>...</title>
    <script type="text/javascript" src="jquery.min.js"></script>
    <script type="text/javascript">
      function foo() {
        $('.datetime').each( function() {
          var t = $(this).text();
          t = new Date(Date.parse(t)).toLocaleString();
          $(this).text(t);
        });
      }
    </script>
  </head>
  <body>
    <div><span class="datetime"><?php echo date(DateTime::RSS, $now); ?></span></div>
    <div><span class="datetime"><?php echo date(DateTime::RSS, $yesterday); ?></span></div>
    <div><span class="datetime"><?php echo date(DateTime::RSS, $someotherdate); ?></span></div>
    <button onclick="foo()">to local time</button>
  </body>
</html>

This prints

Sat, 17 Apr 2010 04:40:15 -0700
Fri, 16 Apr 2010 00:00:00 -0700
Sat, 27 Mar 1976 08:00:00 -0800

in my browser and (since my local timezone is Europe/Berlin, CET, UTC+1/2) after hitting the to local time button

Samstag, 17. April 2010 13:40:15
Freitag, 16. April 2010 09:00:00
Samstag, 27. März 1976 17:00:00


It's now 2013, and as more and more people switch from processing SQL results on PHP side to passing results in JSON and processing on client side, I think moment.js deserves some attention of its own for offering easy replacements to PHP's strtotime() and date() functions in Javascript, plus some more.

Just include:

<script src="SCRIPT_DIR/moment.min.js" type="text/javascript"></script>

Then it's as easy as:

// Simulates ajax response
var data = { someDate: "2023-08-23 11:52:39" }

// .unix() converts to Unix timestamp: 1692816759
moment(data.someDate).unix();

// Displaying it in a readable format
// Aug 23, 11:52 AM
moment("2023-08-23 11:52:39").format('MMM D, hh:mm A');

// Now
moment();

// Support for manipulation and chaining
moment().add('days', 7).subtract('months', 1).hours(15).minutes(0).seconds(0);

You can get the 5.5kb js file here:

http://momentjs.com/

More docs here:

http://momentjs.com/docs/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号