Mahesh Cheliya
Mahesh Cheliya

Reputation: 1364

How to separate date and time in php?

my date format is like : Wednesday, 22 Apr, 2015, 12:39 PM

How i separate date and time like Below ?

> Date :- April 22 2015

> Time :- 12:39 PM

Upvotes: 4

Views: 4610

Answers (5)

chriz
chriz

Reputation: 1345

if you are giving that date as a string. try below code.. first spiting it by space and , will give you the following array

Array
(
    [0] => Wednesday
    [1] => 22
    [2] => Apr
    [3] => 2015
    [4] => 12:39
    [5] => PM
)

following is the code for splitting and extracting date and time seoarately

$dateTime = 'Wednesday, 22 Apr, 2015, 12:39 PM';
$dateArray = array_map('trim', preg_split( "/[\s,]+/", $dateTime ));
$date = $dateArray [2].' '.$dateArray [1].' '.$dateArray [3];
$time = $dateArray [4].' '.$dateArray [5];
echo $date;
echo $time;

Upvotes: 1

Mahadeva Prasad
Mahadeva Prasad

Reputation: 709

Use below code

$dateTime = 'Wednesday, 22 Apr, 2015, 12:39 PM';
 $splitDate = explode(',', $dateTime);
 echo "date => ".$splitDate[1].' '.$splitDate[2];
 echo "time =>".array_pop($splitDate);

Upvotes: 1

Vivek Singh
Vivek Singh

Reputation: 2447

you can use explode like below to separate the string into different pieces and than combine whatever pieces you like in your code

    <?php $date="Wednesday, 22 Apr, 2015, 12:39 PM";
$date=explode(',',$date);

echo "Date".':-'.$date[1].' '.$date[2]."<br/>";
echo "Time".':-'.$date[3];
?>

Upvotes: 1

n-dru
n-dru

Reputation: 9420

First remove the commas and use strtotime:

$dt = 'Wednesday, 22 Apr 2015, 12:39 PM';
$dt = strtotime(str_replace(',', '', $dt));
$d = date('F d Y',$dt);
$t = date('h:i A',$dt);
echo $d,'<br/>',$t;

Output:

April 22 2015
12:39 PM

Upvotes: 7

Prasanga
Prasanga

Reputation: 1038

Use Date and Time string and sperate it below,

$time = new DateTime("2015-04-22 18:00:01");
$date = $time->format('n.j.Y');
$time = $time->format('H:i');

Upvotes: 2

Related Questions