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
  • 12,410
  • 3
  • 41
  • 67
Henrik Petterson
  • 6,862
  • 20
  • 71
  • 155
  • *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
  • 12,410
  • 3
  • 41
  • 67
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
  • 4,005
  • 3
  • 22
  • 42
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
  • 9,082
  • 15
  • 74
  • 164