-2

I post a date input $_POST['date'] with format 2013/11/22 and time $_POST['time'] with format 10:10 AM. Now I need to put both inputs in the mktime function like this:

mktime(10, 10, 0, 11, 22, 2013);

How do I create this?

Jonathan
  • 6,572
  • 1
  • 30
  • 46
Alex.DX
  • 141
  • 1
  • 4
  • 14
  • possible duplicate of [Convert one date format into another in PHP](http://stackoverflow.com/questions/2167916/convert-one-date-format-into-another-in-php) – Glavić Jan 19 '14 at 01:55

3 Answers3

2

You can use DateTime::createFromFormat to create a DateTime object from an arbitrary format. Then you can use that object to get the timestamp (or format the date in another way):

// $_POST['date'] = '2013/11/22';
// $_POST['time'] = '10:10 AM';

$datetime = $_POST['date'] . ' ' . $_POST['time'];
$datetime = DateTime::createFromFormat('Y/m/d h:i A', $datetime);

if ($datetime) {
    $timestamp = $datetime->getTimestamp();
} else {
    echo 'Invalid date or time.';
}

The format in my solution (Y/m/d h:i A) expects leading zeros for all parts of the input (e.g., 2013-01-01 01:01 AM). If the input doesn't use leading zeros, you'll have to change the input format. You can see all supported format characters in the documentation.

Jonathan
  • 6,572
  • 1
  • 30
  • 46
  • This not work. I see error:`Invalid date or time` see DEMO:http://phpfiddle.org/main/code/jme-2z1 – Alex.DX Jan 18 '14 at 17:49
  • 1
    @Alex.DX Sorry, I made two mistakes in the format (`M` instead of `m` and `-` instead of `/`). If you replace the format with `Y/m/d h:i A` in your code, it should work fine! – Jonathan Jan 18 '14 at 17:58
  • yes now worked but this worked for Gregorian date. I need to custom `mktime` function for Arabic to Gregorian timestamp date. I need to this `mktime(10, 10, 0, 11, 22, 2013);` and for Arabic date I change `mktime` to `ARmktime`(custom function) and this worked. – Alex.DX Jan 18 '14 at 18:08
  • Your comment is not quite clear. You also want to parse Arabic dates and get the timestamp? If so, please update your question and include an example, because I'm not familiar with Arabic dates. – Jonathan Jan 18 '14 at 18:11
0

You just use explode() function

$array = explode('/', $_POST['date']);
$arraytwo = explode (':', $_POST['time']);

In this way you'll have two array to populate mktime function.

Also the solution offered by other people will do the work.

Kei
  • 771
  • 6
  • 17
0

You do not need to use mktime to it. Yeah entries are strings, then it is more consistent to use the strtotime function.

//$_POST['date'] = '2013/11/22';
//$_POST['time'] = '10:10 AM';

$dateTime   = "{$_POST['date']}{$_POST['time']}";

$timeStamp  = strtotime($dateTime);

if($timeStamp===false):

  throw new \Exception("The date or time format is not valid!");

endif;
Southman
  • 1
  • 2