学习要点

  • UNIX时间戳
  • 将其他格式的日期转成UNIX时间戳格式
  • 基于UNIX时间戳的日期计算
  • 获取并格式化输出日期
  • 修改PHP的默认时间
  • 微秒的使用

  

Unix时间戳

相关概念

Unix timestamp:从格林威治时间1970年01月01日00时00分00秒起至现在的总秒数。

大部分32位操作系统使用32位二进制数字表示时间。此类系统的Unix时间戳最多可以使用到格林威治时间2038年01月19日03时14分07秒(二进制:01111111 11111111 11111111 11111111)。其后一秒,二进制数字会变为10000000 00000000 00000000 00000000,发生溢出错误,造成系统将时间误解为1901年12月13日20时45分52秒。这很可能会引起软件故障,甚至是系统瘫痪。使用64位二进制数字表示时间的系统(最多可以使用到格林威治时间292,277,026,596年12月04日15时30分08秒)则基本不会遇到这类溢出问题。

搭载64位处理器的iOS设备的时间bug。

PHP将日期和时间转变成UNIX时间戳

  • mktime()函数

    作用:取得一个日期的 Unix 时间戳

    语法格式:

int mktime ([ int $hour = date("H") [, int $minute = date("i") [, int $second = date("s") [, int $month = date("n") [, int $day = date("j") [, int $year = date("Y") ]]]]]] )

  

    特点:对日期运算和验证表现卓越,可以自动校正越界输入。

    示例代码:

//获取当前时间戳

echo mktime();//不带参不推荐使用mktime(),推荐使用time()

echo time();

//时间戳转日期

echo date("Y-m-d",time());

//mktime自动校正越界

echo date("Y-m-d",mktime(0,0,0,12,36,2015)).'<br>';

echo date("Y-m-d",mktime(0,0,0,14,30,2015)).'<br>';

echo date("Y-m-d",mktime(0,0,0,1,1,2015)).'<br>';

echo date("Y-m-d",mktime(0,0,0,1,1,69)).'<br>';//<=70自动解析成1970

echo date("Y-m-d",mktime(0,0,0,1,1,1969)).'<br>';//1969

  

  • strtotime()函数

    语法格式:

int strtotime(string time,[int now])

    示例代码:

// 英文文本解析成时间戳:支持英语国家日期描述字符串

echo date ( "Y-m-d", strtotime ( "8 may 2016" ) );//2016-05-08

echo date ( "Y-m-d", strtotime ( "last monday" ) ); // 最近一个周一

echo date ( "Y-m-d", strtotime ( "now" ) );//现在

echo date ( "Y-m-d", strtotime ( "+1 day" ) );//明天

  

日期的计算

  • 上机练习:制作倒计时
  • 上机练习:给定生日日期,计算年龄
  • 上机练习:十年前
  • 上机练习:三个月前

在PHP中获取日期和时间

getdate()函数:获得日期/时间信息

date()函数:日期和时间格式化输出

当日期和时间需要保存或者计算时,应该使用时间戳作为标准格式。

语法规则:

String date ( string format [,int timestamp] )

修改PHP默认时区

  • 修改php.ini

    修改前:date.timezone = Europe/Paris

    修改后:date.timezone = Etc/GMT-8

  • 设置时区函数date_default_timezone_set()
date_default_timezone_set('PRC');

echo date("Y年m月d日  H:i:s");

  

使用微秒计算PHP脚本执行时间

语法格式:

mixed microtime ([ bool $get_as_float ] )

  

代码示例:

echo microtime();//输出微秒+时间戳

echo '<br>***********<br>';

echo microtime(true);//输出时间戳.微秒

  

上机练习:日历类的设计

日历类:

<?php

/**日历类*/
class Calendar
{
private $year;//当前年
private $month;//当前月
private $days;//当前余月总天数
private $monthStartWeekDay;//当月第一天对应的周几,用于遍历日历的开始 /**构造方法:初始化当前日期参数*/
function __construct()
{
//设置年
$this->year = isset($_GET["year"]) ? $_GET["year"] : date("Y");
//设置月
$this->month = isset($_GET["month"]) ? $_GET["month"] : date("m");
//计算该月第一天是周几
$this->monthStartWeekDay = date("w", mktime(0, 0, 0, $this->month, 1, $this->year));
//计算该月一共有多少天
$this->days = date("t", mktime(0, 0, 0, $this->month, 1, $this->year));
} /**
* 输出日历信息字符串
* @return string 日历字符串
*/
function __toString()
{
$out = '<table align="center">'; //日历以表格形式打印
$out .= $this->changeDate(); //调用内部私有方法用于用户自己设置日期
$out .= $this->weeksList(); //调用内部私有方法打印“周”列表
$out .= $this->daysList(); //调用内部私有方法打印“日”列表
$out .= '</table>'; //表格结束
return $out; //返回整个日历输出需要的全部字符串
} /**
* 输出周列表标题行
*/
private function weeksList()
{
$week = array("日", "一", "二", "三", "四", "五", "六");
$out = "<tr>";
for ($i = 0; $i < count($week); $i++) {
$out .= "<th class='fontb'>" . $week[$i] . "</th>";
}
$out .= "</tr>";
return $out;
} /**
* 输出日历表
*/
private function daysList()
{
$out = "<tr>";
/**输出月日历前的空格*/
for ($i = 0; $i < $this->monthStartWeekDay; $i++) {
$out .= "<td> </td>";
} /**输出当月日期;如果是当前日期则背景深色*/
for ($j = 1; $j < $this->days; $j++) {
$i++;
if ($j == date("d")) {
$out .= "<td class='fontb'>" . $j . "</td>";
} else {
$out .= "<td>" . $j . "</td>";
} if ($i % 7 == 0) {
$out .= "</tr><tr>";
}
} /**日历月份后的空格*/
while ($i % 7 != 0) {
$out .= "<td> </td>";
$i++;
} $out .= "</tr>";
return $out;
} /**上一年*/
private function prevYear($year, $month)
{
$year = $year - 1;
if ($year < 1970) {
$year = 1970;
}
return "year={$year}&month={$month}";
} /**上一个月*/
private function prevMonth($year, $month)
{
if ($month == 1) {
$year = $year - 1;
if ($year < 1970) {
$year = 1970;
$month = 12;
}
} else {
$month--;
}
return "year={$year}&month={$month}";
} /**下一年*/
private function nextYear($year, $month)
{
$year = $year + 1;
if ($year > 2038) {
$year = 2038;
}
return "year={$year}&month={$month}";
} /**下一个月*/
private function nextMonth($year, $month)
{
if ($month == 12) {
$year = $year + 1;
if ($year > 2038) {
$year = 2038;
$month = 12;
}
} else {
$month++;
}
return "year={$year}&month={$month}";
} /**
* 调整年份和月份方法
* @param string $url
*/
private function changeDate($url = "index.php")
{
$out = '<tr>';
$out .= '<td><a href="' . $url . '?' . $this->prevYear($this->year, $this->month) . '">' . '<<' . '</a></td>';
$out .= '<td><a href="' . $url . '?' . $this->prevMonth($this->year, $this->month) . '">' . '<' . '</a></td>'; $out .= '<td colspan="3">';
$out .= '<form>';
$out .= '<select name="year" onchange="window.location=\'' . $url . '?year=\'+this.options[selectedIndex].value+\'&month=' . $this->month . '\'">';
for ($sy = 1970; $sy <= 2038; $sy++) {
$selected = ($sy == $this->year) ? "selected" : "";
$out .= '<option ' . $selected . ' value="' . $sy . '">' . $sy . '</option>';
}
$out .= '</select>';
$out .= '<select name="month" onchange="window.location=\'' . $url . '?year=' . $this->year . '&month=\'+this.options[selectedIndex].value">';
for ($sm = 1; $sm <= 12; $sm++) {
$selected1 = ($sm == $this->month) ? "selected" : "";
$out .= '<option ' . $selected1 . ' value="' . $sm . '">' . $sm . '</option>';
}
$out .= '</select>';
$out .= '</form>';
$out .= '</td>'; $out .= '<td><a href="' . $url . '?' . $this->nextYear($this->year, $this->month) . '">' . '>>' . '</a></td>';
$out .= '<td><a href="' . $url . '?' . $this->nextMonth($this->year, $this->month) . '">' . '>' . '</a></td>';
$out .= '</tr>';
return $out; //返回调整日期的表单 }
}

  

测试文件:

<html>
<head>
<title>日历</title>
<style>
table { border:1px solid #050;} /*给表格加一个外边框*/
.fontb { color:white; background:blue;} /*设置周列表的背景和字体颜色*/
th { width:30px;} /*设置单元格子的宽度*/
td,th { height:30px;text-align:center;} /*设置单元高度,和字段显示位置*/
form { margin:0px;padding:0px; } /*清除表单原有的样式*/
</style>
</head>
<body>
<?php
require "Calendar.class.php"; //加载日历类
echo new Calendar; //直接输出日历对象,自动调用魔术方法__toString()打印日历
?>
</body>
</html>

  

												

PHP11 日期和时间的更多相关文章

  1. [Java]Java日期及时间库插件 -- Joda Time.

    来到新公司工作也有一个多月了, 陆陆续续做了一些简单的项目. 今天做一个新东西的时候发现了 Joda Time的这个东西, 因为以前用的都是JDK原生的时间处理API, 大家都知道Java原生的时间处 ...

  2. SharePoint 2013 日期和时间字段格式设置

    前言 最近碰到一个需求,用户希望修改日期和时间字段的格式,因为自己的环境是英文的,默认的时间格式是[月/日/年]这样的格式,我也是碰到这个问题才知道,这是美式的时间格式,然而用户希望变成英式的时间格式 ...

  3. MySQL 日期、时间转换函数

    MySQL 日期.时间转换函数:date_format(date,format), time_format(time,format) 能够把一个日期/时间转换成各种各样的字符串格式.它是 str_to ...

  4. python笔记7:日期和时间

    Python 提供了一个 time 和 calendar 模块可以用于格式化日期和时间. 时间间隔是以秒为单位的浮点小数. 每个时间戳都以自从1970年1月1日午夜(历元)经过了多长时间来表示. 时间 ...

  5. PHP的日期和时间处理函数

    1. 将日期和时间转变为时间戳 1.1 time() 原型:time(void) 作用:返回当前时间的 UNIX时间戳. 参数:void,可选(即无参数) 1.2 mktime() 原型:int mk ...

  6. VB6.0中,DTPicker日期、时间控件不允许为空时,采用文本框与日期、时间控件相互替换赋值(解决方案)

    VB6.0中,日期.时间控件不允许为空时,采用文本框与日期.时间控件相互替换赋值,或许是一个不错的选择. 实现效果如下图: 文本框txtStopTime1 时间框DTStopTime1(DTPicke ...

  7. Sql Server系列:日期和时间函数

    1. 获取系统当前日期函数GETDATE() GETDATE()函数用于返回当前数据库系统的日期和时间,返回值的类型为datetime. SELECT GETDATE() 2. 返回UTC日期的函数G ...

  8. Sql Server函数全解(四)日期和时间函数

      日期和时间函数主要用来处理日期和时间值,本篇主要介绍各种日期和时间函数的功能和用法,一般的日期函数除了使用date类型的参数外,也可以使用datetime类型的参数,但会忽略这些值的时间部分.相同 ...

  9. SQL Server 日期和时间函数

    http://www.cnblogs.com/adandelion/archive/2006/11/08/554312.html 1.常用日期方法(下面的GetDate() = '2006-11-08 ...

随机推荐

  1. 未能加载文件或程序集“Microsoft.ReportViewer.WebForms, Version=9.0.0.0, Culture=neutral, PublicKeyT

    VS2008开发的网站,本地测试没问题,上传到服务器就出错,提示: 引用内容未能加载文件或程序集“Microsoft.ReportViewer.WebForms, Version=9.0.0.0, C ...

  2. 038--HTML

    一.HTML的定义 1. 超文本标记语言(Hypertext Markup Language,HTML)通过标签语言来标记要显示的网页中的各个部分.一套规则,浏览器认识的规则 2. 浏览器按顺序渲染网 ...

  3. UVa 1611 Crane (构造+贪心)

    题意:给定一个序列,让你经过不超过9的6次方次操作,变成一个有序的,操作只有在一个连续区间,交换前一半和后一半. 析:这是一个构造题,我们可以对第 i 个位置找 i 在哪,假设 i  在pos 位置, ...

  4. Javascript中的回调函数和匿名函数的回调示例介绍

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  5. Gradle技术之四 - Gradle的Task详解

    1 Gradle的Task详解 1 Task定义和配置 2 Task的执行 3 Task的依赖和执行顺序 4 Task类型 5 Task结合gradle的生命周期 6 Task实战 1.1 Task定 ...

  6. 洛谷 - P2280 - 激光炸弹

    https://www.luogu.org/problemnew/show/P2280 二维前缀和差分的模板题.注意学习二维前缀和的求法,不用又down又right的. #include<bit ...

  7. poj3181【完全背包+整数拆分】

    题意: 给你一个数n,在给你一个数K,问你这个n用1-k的数去组合,有多少种组合方式. 思路: 背包重量就是n: 那么可以看出 1-k就是重物,价值是数值,重量是数值. 每个重物可以无限取,问题转化为 ...

  8. [洛谷4329/COCI2006-2007#1] Bond

    Description Everyone knows of the secret agent double-oh-seven, the popular Bond (James Bond). A les ...

  9. matplotlib 绘图实例01:正弦余弦曲线

    该讲的实例结果如下图所示: 第01步:导入模块,并设置显示中文和负号的属性: import matplotlib.pyplot as plt import numpy as np plt.rcPara ...

  10. c语言读取一个文件夹下的全部文件(jpg / png 文件)

    #include <cstdio> #include <cstring> #include <unistd.h> #include<dirent.h> ...