需要更改字符串到日期

时间:2013-10-04 12:57:16

标签: php

我有一些时序字符串,如

$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 个答案:

答案 0 :(得分:2)

您有两个不同的问题:解析字符串到目前为止并转换您的值。

解析字符串到目前为止最终是一个复杂的问题。 strtotimeDateTime可以解析大多数日期格式,但不是全部。 例如,他们不会“只是现在”解析。 当然,您可以使用自己的硬编码值来扩展它。

转换值很简单:

array_map(
    function ($dateString) {
        if ($dateString === 'just now') {
            $dateString = 'now';
        }
        return (new DateTime($dateString))->format('Y-m-d H:i:s');
    },
    $timing_strings
);

答案 1 :(得分:1)

您应该可以使用strtotime

转换大多数时间字符串

答案 2 :(得分: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);
?>

WORKING CODE

答案 3 :(得分: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
)