php 字符串转时间戳_PHP中strtotime()函数,将任意日期的字符串转换成Unix时间戳...

我们上一篇文章说了一个mktime()函数,可以将以数值形式表现的日期和时间转换成Unix时间戳,那么这篇文章就说一说,如何把任何一个用字符串表示的日期,转成Unix时间戳。PHP中的strtotime()函数

strtotime()函数

定义:

strtotime() 函数将任何字符串的日期时间描述解析为 Unix 时间戳(自 January 1 1970 00:00:00 GMT 起的秒数)。

注意:如果年份表示使用两位数格式,则值 0-69 会映射为 2000-2069,值 70-100 会映射为 1970-2000。

注意:请注意 m/d/y 或 d-m-y 格式的日期,如果分隔符是斜线(/),则使用美洲的 m/d/y 格式。如果分隔符是横杠(-)或者点(.),则使用欧洲的 d-m-y 格式。为了避免潜在的错误,您应该尽可能使用 YYYY-MM-DD 格式或者使用 date_create_from_format() 函数。

语法:int strtotime ( string $time [, int $now = time() ] )

解释:

time必需。规定日期/时间字符串。

now可选。规定用来计算返回值的时间戳。如果省略该参数,则使用当前时间。举例说明:

利用strtotime()函数,将带有英文字母的日期,转换成数字日期

代码<?php

//飞鸟慕鱼博客

$d=strtotime("10:38pm May 15 2018");

echo "创建日期是 " . date("Y-m-d H:i:s", $d);

?>

代码示意图:

88cbab2b8a5e966564943e1fe34b1c1c.png

代码动行结果:创建日期是 2018-05-15 22:38:00

代码说明:

代码中的,May,表示为“五月”,所以在输出格式化的日期后,为05;我们可以利用strtotime()函数做很多有意思的事

比如下例的代码,获取明天的日期,下周一的日期,二个月后的日期

代码

//飞鸟慕鱼博客

echo '当前日期:'.date('Y-m-d').' 星期'.date('w').'
';

//明天的日期

$d=strtotime("tomorrow");

echo '明天日期:'.date("Y-m-d", $d) . "
";

//下周一的日期

$d=strtotime("next monday");

echo '下周一日期:'.date("Y-m-d", $d) . "
";

//二个月后的日期

$d=strtotime("+2 Months");

echo '二个月后的日期:'.date("Y-m-d", $d) . "
";

?>

代码示意图

9a570f7690767ffc8bdc0bb200608347.png

运动结果当前日期:2018-07-20

星期5明天日期:2018-07-21

下周一日期:2018-07-23

二个月后的日期:2018-09-20

PS:mktime()与strto在使用方法上并没有太大的区别,所以上面的实例通过稍微的改动在mktime()函数上也可以实现!

补充,利用strtotime()进行各种时间判断输入代码

代码echo "今天:",date("Y-m-d",time()),"
";

echo "今天:",date("Y-m-d",strtotime("18 june 2008")),"
";

echo "昨天:",date("Y-m-d",strtotime("-1 day")), "
";

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

echo "一周后:",date("Y-m-d",strtotime("+1 week")), "
";

echo "一周零两天四小时两秒后:",date("Y-m-d G:H:s",strtotime("+1 week 2 days 4 hours 2 seconds")), "
";

echo "下个星期四:",date("Y-m-d",strtotime("next Thursday")), "
";

echo "上个周一:".date("Y-m-d",strtotime("last Monday"))."
";

echo "一个月前:".date("Y-m-d",strtotime("last month"))."
";

echo "一个月后:".date("Y-m-d",strtotime("+1 month"))."
";

echo "十年后:".date("Y-m-d",strtotime("+10 year"))."
";

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值