php strtotime输入格式


php strtotime input format

As strtotime()将有效的日期格式转换为UNIX时间戳。如果我的输入是dd-mm-yyyy格式(例如09-10-2014)和mm-dd-yyyy格式(例如,10-09-2014),如何确保strtotime将其转换为正确的时间戳?

您可以使用DateTime

<?php
$date = DateTime::createFromFormat('d-m-Y', '05-09-2014');
print_r( $date->getTimestamp() );
$date = DateTime::createFromFormat('m-d-Y', '09-05-2014');
print_r( $date->getTimestamp() );

实时预览

如果您确切地知道输入格式,您可以执行以下操作:

//对于DD-MM-YYYY

$date = '09-05-2014'; // 09 May 2014
$converted = implode('-',array_reverse(explode('-', $date))); // returns 2014-05-09

//对于MM-DD-YYYY,如上Mark Baker所述

$date = '05-09-2014'; // 09 May 2014
$converted = date('Y-m-d', strtotime(str_replace('-','/', $date))); // returns 2014-05-09