10

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 special date function I should be using? Or something else?

Thanks!

8 Answers8

18

One way would be to do this:

$time = strtotime($date);
$m = date('m', $time);
$d = date('d', $time);
$y = date('Y', $time);
Doug Hays
  • 1,507
  • 11
  • 13
14

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);
Jeremy
  • 1
  • 85
  • 340
  • 366
Dominic Rodger
  • 97,747
  • 36
  • 197
  • 212
5

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"));
?>
Glen Tankersley
  • 113
  • 1
  • 2
4

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');
gagarine
  • 4,190
  • 2
  • 30
  • 39
2

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);
}
Daniel
  • 374
  • 2
  • 5
2

how about this:

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

A quick one liner.

Carson Myers
  • 37,678
  • 39
  • 126
  • 176
0

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'));
George Lund
  • 1,269
  • 12
  • 16
-3

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

Bill H
  • 15
  • 2
  • Why would one want to avoid explode? *IF* the date is *ALWAYS* in the same format, explode will work perfectly, and as @GiDo implies, will be self documenting in terms of intent. If one wants to avoid the array, then `list` the elements out to distinct variables. – Sepster Jul 30 '15 at 10:06