關於 PHP, Linux, Open Source 及個人生活記載的網誌。
RSS icon
  • PHP 的日期計算

    Posted on September 12th, 2009 Sam Tang 1 comment

    在 PHP 內計算兩個日期之間的差距的話,可以先將日期轉成 Unix timestamp 的數值然後再作計算。例如要計算兩個日期 01/01/2009 及今天的日期差距,可以這樣做:

    PHP:
    1. <?php
    2. // 將日期以 "/" 附號分隔, 得出 日, 月, 年
    3. $time = explode("/", "01/01/2009");
    4.  
    5. // 將 01/01/2009 轉換成 Unix timestamp
    6. $unix_time = mktime(0, 0, 0, $time[0], $time[1], $time[2]);
    7.  
    8. // 計算 $unix_time 和現在的差距, 並除 86400 (一天有 86400 秒)
    9. $time_diff = (time() - $unix_time) / 86400;
    10. // 只擷取整數部份
    11. $time_diff = (int) $time_diff;
    12.  
    13. echo "01/01/2009 距離現在 "$time_diff . " 天.";
    14. ?>


     

    One response to “PHP 的日期計算”

    1. 是 月,日,年 不是 日,月,年
      第二行

    Leave a reply

    *
    To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
    Click to hear an audio file of the anti-spam word