简体   繁体   English

PHP:检查两个字符串是否为日期以及是否为同一日期

[英]PHP: Check two strings if they are the dates and if they are the same date

I need to check if two strings I have are dates and if they are the same date.我需要检查我拥有的两个字符串是否是日期以及它们是否是相同的日期。 They come in different formats ie它们有不同的格式,即

DD-MM-YYYY and YYYY-MM-DD DD-MM-YYYY 和 YYYY-MM-DD

I did something that works but looks cumbersome and was wondering if there was something more succint and clever我做了一些可行但看起来很麻烦的事情,想知道是否有更简洁和聪明的东西

if ((substr($old, 0, 4) == substr($new, 6, 4) && substr($old, 5, 2) == substr($new, 3, 2) && substr($old, 8, 2) == substr($new, 0, 2) && strlen($new)==10 && strlen($old) == strlen($new) && strtotime($old) == strtotime($new))) {

As unlikey as it is, we could have literally the text "DD-MM-YYYY" and YYYY-MM-DD" but obviously they aren't dates but it would still pass the test尽管不太可能,但我们可以从字面上看到文本“DD-MM-YYYY”和 YYYY-MM-DD”,但显然它们不是日期,但它仍然可以通过测试

UPDATE更新

if ((strtotime($old)===strtotime($new) && DateTime::createFromFormat('Y-m-d', $old) !== FALSE && DateTime::createFromFormat('d-m-Y', $new) !== FALSE)) {

Something like this?像这样的东西? (modified from here ) (从这里修改)

function validate_date($date, $format = 'Y-m-d') {
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) === $date;
}

if(validate_date($old) && $validate_date($new, 'd-m-Y') && strtotime($old) == strtotime($new)) {
    //do stuff
}

strtotime() will return false if it can't create a timestamp out of the provided string.如果strtotime()无法从提供的字符串中创建时间戳,它将返回 false。 So the following should work:所以以下应该工作:

if ( strtotime($old) && strtotime($new) && strtotime($old) == strtotime($new) ) {
    echo 'Same date!';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM