dongzaijiao4863
2013-08-19 18:43
浏览 126
已采纳

将PHP回显日期转换为客户端本地时间

This is my first post. I have a problem that i can't seem to resolve. Here it goes:

I have a PHP script that prints the date of an event to the page:

$event_datetime = date("g:i A (m/d/y)", strtotime($row['event_time']));
echo $event_datetime

I want to use Javascript to convert that $event_datetime into client local timezone preferably or local client computer time.

Any ideas ?

Thanks in advance !

图片转代码服务由CSDN问答提供 功能建议

这是我的第一篇文章。 我有一个问题似乎无法解决。 在这里:

我有一个PHP脚本,它将事件的日期打印到页面:

  $ event_datetime = date(  “g:我是(m / d / y)”,strtotime($ row ['event_time'])); 
echo $ event_datetime 
   
 
 

我想要 使用Javascript将$ event_datetime转换为客户端本地时区或本地客户端计算机时间。

任何想法?

提前致谢!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dpsq8476 2013-08-19 18:50
    已采纳

    You can use php to convert all dates into a timezone with:

    date_default_timezone_set('America/Los_Angeles');
    

    For example:

    $time = time();
    $date = date(DATE_RFC822, $time);
    echo $date . PHP_EOL;
    
    date_default_timezone_set("Australia/Perth");
    $date = date(DATE_RFC822, $time);
    echo $date. PHP_EOL;
    

    Output:

    Mon, 19 Aug 13 18:49:40 +0000
    Tue, 20 Aug 13 02:49:40 +0800
    

    You would just need to get the clients timezone from somewhere (a preference saved in the database or getting it via javascript for example).

    See Getting the client's timezone in JavaScript for using javascript

    点赞 打赏 评论
  • doulutian4843 2013-08-19 18:47

    Instead of echoing a date to javascript, just echo the timestamp and use javascripts date object.

    var date = new Date(<?php echo strtotime($row['event_time']) * 1000); ?>);
    

    You can now use javascripts date object to print out the time however you want. Like this:

    date.toLocaleDateString();
    //The default output will be the users' timezone (the client where the javascript is being executed), but can be configured with the options argument
    

    See:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

    For more on the javascript date object

    点赞 打赏 评论
  • dongyue0225 2013-08-20 15:51

    I got the answer to what i was looking for, but i thank you guys for taking the time to help. Your solution was great but not what i needed. Ok, here is how i got it:

    Keeping in mind that $row['event_time'] is a datetime value saved on the database on UTC timezone.

    while($row = $result->fetch_assoc())
    {
        $s_date = new DateTime($row['event_time'],new DateTimeZone('UTC'));
        $s_date->setTimezone(new DateTimeZone('America/New_York'));
        $start_event_time = $s_date->format('g:i:s A (m/d/y)');
        echo $start_event_time;
    }
    

    You can create an additional script that gets the current user timezone and change America/New_York to make it more dynamic.

    Hope it helps someone with my same issue.

    点赞 打赏 评论

相关推荐 更多相似问题