I have some timing strings like,
$timing_strings =array(1=>'just now', 2=>'3 minutes ago', 3=>'3 weeks ago');
The question is i want to change that type of strings into particular date-time format. How can i do this..? I need an output like,
array(
1=>'2013-10-04 06:24:24',
2=>'2013-10-04 06:21:24',
3=>'2013-09-14 06:24:24'
);
I couldn't get any solution for this, any ideas appreciated. thanks in advance
You have two separate problems: parsing string to date and converting your values.
Parsing string to date ultimately is a complex problem. strtotime
and DateTime
can parse most date formats, but not all. They won't parse "just now", for example. You can extend that with your own hardcoded values, of course.
Converting values, though, is simple:
array_map(
function ($dateString) {
if ($dateString === 'just now') {
$dateString = 'now';
}
return (new DateTime($dateString))->format('Y-m-d H:i:s');
},
$timing_strings
);
You should be able to convert most time strings with strtotime
try this:
<?
$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);
?>
used this code:
<?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'));
}
}
Output
Array
(
[0] => 2013-10-04 18:47:44
[1] => 2013-10-04 18:44:44
[2] => 2013-09-13 18:47:44
)