PHP Date ( I need to use)

WBOY
Release: 2016-06-23 13:14:41
Original
878 people have browsed it

本文记录项目中用到的 PHP Date 相关,备忘。

日期格式约定为 xx-xx-xx 格式(字符串),例如 2016-03-09。

xx-xx-xx -> 时间戳

$date = "2016-03-09";$timestamp = strtotime($date);  // 1457481600
Copy after login

这是完完全全的服务器的时间戳(ps:这些函数依赖于服务器的本地设置,如果默认设置的话是零时区),"2016-03-09" 这个日期是零时区(本初子午线)的时间。如果要在客户端获取该时间戳,可以这样:

var timestamp = Date.UTC(2016, 2, 9) / 1000; // 1457481600
Copy after login

作为对比:

var date = new Date(2016, 2, 9);var timestamp = +date / 1000; // 1457452800
Copy after login

而 (1457452800 - 1457481600) / 3600 = -8。

因为 date 获取的变量值是客户端本地时间。而本地(东八区)2016 年 3 月 9 日时,零时区应该是 2016 年 3 月 8 日 16 点,所以时间戳会小。详见 Javascript Date。

时间戳 -> xx-xx-xx

$timestamp = 1457481600;$date = date("Y-m-d", $timestamp);  // 2016-03-09
Copy after login

获取当前时间、昨天时间等(xx-xx-xx 格式)

// 获取当前时间$today = date("Y-m-d");  // 2016-03-09// 获取昨天时间$yesterday = date("Y-m-d", strtotime('-1 days')); // 2016-03-08
Copy after login

改变时区

PHP 获取的都是服务器的时间,而默认是零时区,如果要改成东八区,可以这样:

date_default_timezone_set("Asia/Shanghai");$time = date("Y-m-d H:i:s"); // 东八区当地时间
Copy after login

其他

  • getdate() 函数 获取当前时间各种信息
  • date() 函数 格式化时间
  • strtotime() 函数 根据具体日期获取时间戳
  • time() 函数 当前时间时间戳
  • date (php.net)
  • PHP Date / Time 函数 (w3school)
  • Related labels:
    source:php.cn
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!