来自 PHP 的 time() 的 JavaScript 可读日期/时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2658023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:21:16  来源:igfitidea点击:

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

phpjavascriptdatetime

提问by Lyon

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"?

是否可以让 JavaScript 计算从 PHPtime()函数返回的时间戳并以可读格式呈现,例如“Sun, 18th April 2010 at 4:00 pm”?

回答by Gumbo

Use the Dateobjectto do that:

使用Date对象来做到这一点:

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

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

您需要将 Unix 时间戳乘以 1000,因为Date预计时间戳以毫秒为单位。

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

并且要格式化日期,您可以使用此Date.format方法Date没有内置)。

回答by Pointy

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?

当您在芝加哥有一台服务器,而有人在夏威夷使用您的网站时,问题就出现了,比如在一个聚会之后——毫无疑问,其中一个“luau”事件,包括烤猪和草裙舞女,一个在温暖的热带天空下罕见的夜晚,异国情调的花朵散发着海风的味道——现在已经晚了。我的天,快半夜了!当我给她写关于聚会的事时,妈妈会怎么想?

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.

我们的派对爱好者在晚上 11:30 坐下来使用您的网站。现在,当然,在夏威夷以东相当远的地方,您的服务器认为现在是早上 5 点 30 分,而该日期比我们参加聚会的人在给妈妈的速记中记下的日期晚了一天。因此,您的服务器将其时间值写入网页,如此处的答案中所述,并且 - 正确地 - 夏威夷当地时间显示在我们参加聚会的酒店房间的页面上。

The problem is this: if that localtime 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 wherea 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 serveror 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.

你当然可以有相反的问题。也就是说,如果您的服务器总是在其本地时区呈现日期,那么世界其他地方的用户将看到令人困惑(显然是错误的)日期和时间值,因此界面必须明确这些值的含义。当您的站点提供涉及日程安排的服务时,这些问题就变得很重要。如果可以安排操作,重要的是界面保持水平,以便“4 月 30 日晚上 10:00”表示服务器上的日期和时间或安排安排的语言环境中的日期和时间. 无论是哪种情况,您都必须小心保持一致。

回答by VolkerK

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.

除了数字 unix 时间戳,您还可以发送Date.parse()理解的日期的文本表示。
也许这只是我对全球变暖的贡献,但我认为使用一种更具人类可读性并包含时区信息的格式是有好处的。

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 timebutton

在我的浏览器中点击to local time按钮后(因为我的本地时区是欧洲/柏林、欧洲中部时间、UTC+1/2)

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

回答by Scott Yang

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.

现在是 2013 年,随着越来越多的人从在 PHP 端处理 SQL 结果转向在 JSON 中传递结果并在客户端处理,我认为 moment.js 值得关注它自己,因为它可以轻松替代 PHP 的 strtotime() 和Javascript 中的 date() 函数,以及更多。

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:

你可以在这里得到 5.5kb 的 js 文件:

http://momentjs.com/

http://momentjs.com/

More docs here:

更多文档在这里:

http://momentjs.com/docs/

http://momentjs.com/docs/