Dodinas
Dodinas

Reputation:

Parse m/d/Y formatted date string into $m, $d, and $y variables

If I've got a date string:

$date = "08/20/2009";

And I want to separate each part of the date:

$m = "08";
$d = "20";
$y = "2009";

How would I do so?

Is there a dedicated date function I should be using?

Upvotes: 10

Views: 26383

Answers (8)

George Lund
George Lund

Reputation: 1276

For internationalized date parsing, see IntlDateFormatter::parse - http://php.net/manual/en/intldateformatter.parse.php

For example:

$f = new \IntlDateFormatter('en_gb', \IntlDateFormatter::SHORT, \IntlDateFormatter::NONE);
$dt = new \DateTime();
$dt->setTimestamp($f->parse('1/2/2015'));

Upvotes: 0

gagarine
gagarine

Reputation: 4338

If you have a given format you should use a date object.

$date = DateTime::createFromFormat('m/d/Y', '08/20/2009');
$m = $date->format('m');
$d = $date->format('d');
$y = $date->format('Y');

Note you can certainly use only one call to DateTime::format().

$newFormat = $date->format('d-m-Y');

Upvotes: 4

Glen Tankersley
Glen Tankersley

Reputation: 113

Check out PHP's date_parse function. Unless you're sure input will always be in a consistent format, AND you validate it first, it is much more stable and flexible, (not to mention easier), to let PHP try to parse the format for you.

e.g.

<?php
//Both inputs should return the same Month-Day-Year
print_r(date_parse("2012-1-12 51:00:00.5"));
print_r(date_parse("1/12/2012"));
?>

Upvotes: 5

Dominic Rodger
Dominic Rodger

Reputation: 99751

explode will do the trick for that:

$pieces = explode("/", $date);
$d = $pieces[1];
$m = $pieces[0];
$y = $pieces[2];

Alternatively, you could do it in one line (see comments - thanks Lucky):

list($m, $d, $y) = explode("/", $date);

Upvotes: 14

Carson Myers
Carson Myers

Reputation: 38564

how about this:

list($m, $d, $y) = explode("/", $date);

A quick one liner.

Upvotes: 2

Bill H
Bill H

Reputation: 15

Dominic's answer is good, but IF the date is ALWAYS in the same format you could use this:

$m = substr($date,0,2);
$d = substr($date,3,2);
$y = substr($date,-4);

and not have to use an array or explode

Bill H

Upvotes: -3

Daniel
Daniel

Reputation: 374

Is it always like that? Or will it be in any sort of file format?

Try strtotime.

Something like:

if(($iTime = strtotime($strDate))!==false)
{
 echo date('m', $iTime);
 echo date('d', $iTime);
 echo date('y', $iTime);
}

Upvotes: 2

Doug Hays
Doug Hays

Reputation: 1507

One way would be to do this:

$time = strtotime($date);
$m = date('m', $time);
$d = date('d', $time);
$y = date('Y', $time);

Upvotes: 18

Related Questions