0

I am trying to convert a date into a different format, but when I do I always get 1970-01-01. Below is a copy of my code.

 $courseDate = $_SESSION['get_course_date']; //value returns '17/03/2014 - Standard Course'
 $regex='((?:(?:[0-2]?\\d{1})|(?:[3][01]{1}))[-:\\/.](?:[0]?[1-9]|[1][012])[-:\\/.](?:(?:[1]{1}\\d{1}\\d{1}\\d{1})|(?:[2]{1}\\d{3})))(?![\\d])'; 
 if ($c=preg_match_all ("/".$regex."/is", $courseDate, $matches)){ //use regex to get just he date
   $get_date=$matches[1][0]; // returns 17/3/2014
   echo date('Y-m-d', $get_date); // output 1970-01-01
 }

Any feedback would be great.

Cheers

3
  • your doing it the hard way, see related >> Commented Feb 5, 2014 at 2:29
  • what format do you want to achieve? Commented Feb 5, 2014 at 2:29
  • 1
    1970-01-01 is the epoch date. Something is setting your timestamp to 0 Commented Feb 5, 2014 at 2:30

1 Answer 1

4

Your issue is due to date() requiring a unix timestamp as its second parameter. You are giving it a date string. You can use strtotime() to convert your date to a unix timestamp. We also have to use str_replace() to change the slashes to dashes. This is due to strtotime() defaulting to US format when it sees the / separator. By changing it to a dash it defaults to European format:

echo date('Y-m-d', strtotime(str_replace('/', '-', $get_date)));

Here's an alternative solution that should be easier to manage:

$string = '17/03/2014 - Standard Course';
list($date) = explode(' - ', $string);
$dt = DateTime::createFromFormat('d/m/Y', $date);
echo $dt->format('Y-m-d');

See it in action

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.