dongyiyu3953 2015-02-11 10:32
浏览 53
已采纳

PHP:如何根据时间和日期显示内容?

I need to show contents based on a specific date and time in a php page. I need to show content1 upto a certain date, content2 for a limited time (between 2 defined dates), and content3 after the expiry date and time. Moreover, I need the possibility of changing the timezone, so the time should be provided by the server.

What I got so far is the following:

<?php 
$exp_date = "2009-07-20";
$exp_date2 = "2009-07-27";
$todays_date = date("Y-m-d");
$today = strtotime($todays_date);
$expiration_date = strtotime($exp_date);
$expiration_date2 = strtotime($exp_date2);
if ($expiration_date > $today)
{ ?>
<!-- pre-promotion week content -->
<?php } else if ($expiration_date2 > $today) { ?>
<!-- promotion week content -->
<?php } else { ?>
<!-- expired/post-promotion week content -->
<?php } ?>

The problem is that this script takes into account only the date and not the time.

  • 写回答

2条回答 默认 最新

  • dphj737575 2015-02-11 10:49
    关注

    You should be using the built-in DateTime objects: http://php.net/manual/en/book.datetime.php

    You should also be setting the timezone: http://php.net/manual/en/function.date-default-timezone-set.php

    date_default_timezone_set("America/New_York");
    

    Or you can set the timezone per object:

    $exp_date = new DateTime("2009-07-20", new DateTimeZone("America/Los_Angeles"));
    $exp_date2 = new DateTime("2009-07-27", new DateTimeZone("America/Los_Angeles"));
    $today = new DateTime();
    if($today < $exp_date) {
       /*...*/
    } elseif($today < $exp_date2) {
       /*...*/
    } else {
       /*...*/
    }
    

    Note: I purposefully used two different timezones, to show that you can have your server in one zone, and work with dates from other zones. For example:

    $ny = new datetime('2015-02-11 05:55:00', new DateTimeZone('America/New_York'));
    $la = new datetime('2015-02-11 02:55:00', new DateTimeZone('America/Los_Angeles'));
    var_dump($ny == $la); // bool(true)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!