0

my question is trivial i think, yet i cant figure out how to solve it.

I have a string that contains a date in the following format:

$date=('25/8/1990');

I want to convert it to:

1990-8-25

I tried to do the following:

$newdate=date('Y-m-d',strtotime($date));

But the result i get is

1969-12-31

instead of

1990-8-25.

Thank you

Xaris Rg
  • 63
  • 8
  • 1
    possible duplicate of [Convert one date format into another in PHP](http://stackoverflow.com/questions/2167916/convert-one-date-format-into-another-in-php) – Matteo Tassinari May 20 '15 at 06:59
  • Use `DateTime::createFromFormat` to turn date string into DateTime object, then `DateTime::format` to output in desired string format. – Anthony May 20 '15 at 07:01

4 Answers4

1

Use DateTime interface. -

<?php

$date = '25/8/1990';

$newDate = new DateTime(str_replace('/', '-', $date));

echo $newDate->format('Y-n-d');

Output

1990-8-25
Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
1

You can also use DateTime as

$date = '25/8/1990';
$date = DateTime::createFromFormat('d/n/Y', $date);
echo $date->format('Y-n-d');//1990-8-25
Narendrasingh Sisodia
  • 21,247
  • 6
  • 47
  • 54
0

Use DateTime::createFromFormat if the original format is consistent:

$date = '25/8/1990';
$date_obj = DateTime::createFromFormat('j/n/Y', $date);
$date = $date_obj->format('Y-n-j');
Anthony
  • 36,459
  • 25
  • 97
  • 163
0

Use date_parse_from_format() or strptime(). Auto-guessing month/day order placement is not very sane, so avoid strtotime().

<?php
$strdate='25/8/1990';

$darray=date_parse_from_format("d/m/Y", $strdate);
$newstr=date("Y-m-d", mktime(0, 0, 0, $darray['month'], $darray['day'], $darray['year']));

echo $newstr; //produces 1990-08-25

?>
sivann
  • 2,083
  • 4
  • 29
  • 44