1

我有一些计时字符串,例如,

$timing_strings =array(1=>'just now', 2=>'3 minutes ago', 3=>'3 weeks ago');

问题是我想将这种类型的字符串更改为特定的日期时间格式。我怎样才能做到这一点..?我需要一个输出,例如,

array(
1=>'2013-10-04 06:24:24',
2=>'2013-10-04 06:21:24',
3=>'2013-09-14 06:24:24'
);

我对此没有任何解决方案,任何想法表示赞赏。提前致谢

4

4 回答 4

2

您有两个单独的问题:将字符串解析为日期并转换您的值。

解析迄今为止的字符串最终是一个复杂的问题。 strtotime并且DateTime可以解析大多数日期格式,但不是全部。例如,他们不会解析“刚刚”。当然,您可以使用自己的硬编码值来扩展它。

但是,转换值很简单:

array_map(
    function ($dateString) {
        if ($dateString === 'just now') {
            $dateString = 'now';
        }
        return (new DateTime($dateString))->format('Y-m-d H:i:s');
    },
    $timing_strings
);
于 2013-10-04T12:58:25.780 回答
1

您应该能够将大多数时间字符串转换为strtotime

于 2013-10-04T12:58:55.897 回答
1

尝试这个:

<?
$timing_strings =array(1=>'just now', 2=>'3 minutes ago', 3=>'3 weeks ago');
foreach ($timing_strings as $time){
    if ($time == 'just now') $time = 'now';
    $arrTime[] = date("Y-m-d H:i:s",strtotime($time));
}

print_r($arrTime);
?>

工作代码

于 2013-10-04T13:05:14.570 回答
0

使用此代码:

<?php

$timing_strings =array(1=>'just now', 2=>'3 minutes ago', 3=>'3 weeks ago');
$new_arr=array();
foreach ($timing_strings as $time) {
    $new_arr[]  = check_time($time);
}

echo "<pre>";
print_r($new_arr);
echo "</pre>";
exit;

function check_time($time) {
    if (strpos($time,'just now') !== false) {
        return  date("Y-m-d H:i:s",strtotime('now'));
    }elseif (strpos($time,'minutes ago') !== false) {
        return  date("Y-m-d H:i:s",strtotime('-'.(int)$time.' minutes'));
    }elseif (strpos($time,'weeks ago') !== false) {
        return  date("Y-m-d H:i:s",strtotime('-'.((int)$time*7).' days'));
    }
}

输出

Array
(
    [0] => 2013-10-04 18:47:44
    [1] => 2013-10-04 18:44:44
    [2] => 2013-09-13 18:47:44
)
于 2013-10-04T13:16:48.280 回答