5
echo $_POST['time']."<br/>";
echo $_POST['day']."<br/>";
echo $_POST['year']."<br/>";
echo $_POST['month']."<br/>";

I have value store like this now I want to create a timestamp from these value. How to do that in PHP? Thanks in advance

3
  • What do these values look like? I.e., what would the above code print out? Commented Apr 22, 2010 at 12:56
  • these values are coming from a form so i was checking it on the action page. time is 00 for 0000hrs 01 for 0100hrs only time in hours user can select for e.g. if user want 1300 hrs of Apr 19,2010 code will print 13 19 4 2010 Commented Apr 22, 2010 at 13:02
  • date formatting is locale specific. Some of the solutions below use problematic formats. It's better to use a datetime standard like ISO8601 en.wikipedia.org/wiki/ISO_8601 as that will cause the fewest problems. You can always format your output to suit your locale, but if your storage engine confuses 03-09-2001 with 09-03-2001, you'll store the wrong date. Better just to say 2001-03-09 when you mean Mar 9th. Commented Apr 22, 2010 at 14:47

4 Answers 4

7

You can use mktime(). Depending on the format of $_POST['time'], you split it into hour/min/sec and then use

$timestamp = mktime($hour, $min, $sec, $month, $day, $year)
Sign up to request clarification or add additional context in comments.

Comments

1
echo mktime(0,0,0,$_POST['month'],$_POST['day'],$_POST['year']);

I don't know in what format your time is, so, you probably need to explode() it and then put the values into the three first parameters of mktime() like:

$_POST['time'] = '8:56';
$time = explode(':',$_POST['time']);
echo mktime($time[0],$time[1],0,$_POST['month'],$_POST['day'],$_POST['year']);

Comments

0

Use a DateTime object. The parsing is done for you and you can control for TimeZone differences so that daylight savings time doesn't cause issues.

$datetimestring="{$_POST['year']}-{$_POST['month']}-{$_POST['day']} {$_POST['time]}";
$dt= date_create($datetimestring);//optional 2nd argument is TimeZone, so DST won't bite you
echo $dt->format('U');

Comments

0

Another option is strtotime:

$time = "{$_POST['time']} {$_POST['month']}/{$_POST['day']}/{$_POST['year']}";
$timestamp = strtotime($time);

If $_POST['time'] is already in hours and minutes (HH:MM format), then this saves you the step of exploding and parsing it. strtotime can parse a dizzying number of strings into valid times.

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.