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

deceze
  • 510,633
  • 85
  • 743
  • 889
Abhishek
  • 113
  • 1
  • 2
  • 10
  • What do these values look like? I.e., what would the above code print out? – deceze Apr 22 '10 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 – Abhishek Apr 22 '10 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 http://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. – dnagirl Apr 22 '10 at 14:47

4 Answers4

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)
Matteo Riva
  • 24,728
  • 12
  • 72
  • 104
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']);
Tower
  • 98,741
  • 129
  • 357
  • 507
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');
dnagirl
  • 20,196
  • 13
  • 80
  • 123
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.

Josh
  • 10,961
  • 11
  • 65
  • 108