0

I have date in this format 'm-d-Y' (12-31-2017). I want to convert it into a timestamp. Normally, this works:

$timestamp = strtotime($date);

But if I am not mistaken, that works with 'd/m/Y' and not 'm/d/Y'.

What's the solution here?

Aniket Sahrawat
  • 11,710
  • 3
  • 36
  • 63
Henrik Petterson
  • 6,776
  • 19
  • 65
  • 144
  • *I have date in this format 'm/d/Y' (12-31-2017)* - that string doesn't match that format. For reference, `strotime` works fine with m/d/Y dates, but it's always cleaner to use `DateTime::createFromFormat`. – iainn Dec 28 '17 at 11:34

4 Answers4

2

You can use DateTime::createFromFormat() and then call getTimestamp() on the Object:

//first create DateTime Object
$datetime = DateTime::createFromFormat('m-d-Y', '12-31-2017');
//get timestamp from DateTime
echo $datetime->getTimestamp();
Aniket Sahrawat
  • 11,710
  • 3
  • 36
  • 63
0

Try this code .

<?php
$d=strtotime("12/31/2017");
echo "Created date is " . date("m-d-Y h:i:sa", $d);
?>

Output

for more Information about date time format then read PHP Manual

Bilal Ahmed
  • 3,889
  • 3
  • 21
  • 40
0

You can change date according your format :

$date = '12/31/2017';

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

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

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

if Timestamp

$timestamp = date('m-d-Y h:i:s', strtotime($date));
0

An another solution is the following:

//CONVERT the time string from the desired format
$dateTime=DateTime::createFromFormat('m/d/Y',$date);

echo "UNIX TIMESTAMP method 1".$date->format("U");
// false
echo "UNIX TIMESTAMP method 2".$date->getTimestamp();
Dimitrios Desyllas
  • 7,732
  • 8
  • 58
  • 129