Converting separate month, day and year values into a timestamp
I have a month value (1-12), day val开发者_运维问答ue (1-31), and a year value (2010,2011,2012). I also have a hour value and a minute value.
How can I give this to strtotime()
in a way it can convert it to a timestamp?
why convert string to date when you already know year month and date.
use setDate funtion
<?php
$date = new DateTime();
$date->setDate(2001, 2, 3);
echo $date->format('Y-m-d');
?>
Given the variables $year
$month
$day
$hour
$minute
you can do:
strtotime("$year-$month-$day $hour:$minute");
Be careful to enclose the variables with "
, never in this case with '
.
UPDATE (thanks to comments of @Clockwork and @Tadeck):
In case there is a variable $timeofday
that represents the time of day (i.e. AM or PM),
then you can parse it this with:
strtotime("$year-$month-$day $hour:$minute$timeofday");
that is to say, just attach that variable to the end of the text.
Is strtotime
the best tool for this job? What about mktime()
?
$time = mktime($hour, $minute, 0, $month, $day, $year);
You can provide it to function strtotime()
in many ways, as mentioned in documentation. Some examples include:
$your_time = strtotime('12/31/2011 9:59');
$your_time = strtotime('2011-12-31 9:59');
$your_time = strtotime('December 31, 2011 9:59');
etc. It really is very flexible.
You can find the list of valid formats in the documentation, and that is (from the "Compound Formats" list in the mentioned documentation) for example:
10/Oct/2000:13:55:36 -0700
,2008:08:07 18:11:31
,2008-08-07 18:11:31
,2008-07-01T22:35:17.02
,2008-07-01T22:35:17.03+08:00
,20080701T22:38:07
,20080701T9:38:07
,20080701t223807
,20080701T093807
,2008-7-1T9:3:37
,
(this is really copy of the documentation)
Use it like this strtotime("YYYY-mm-DD HH:MM AM/PM")
:
echo date("d F Y h:i:s A", strtotime("2011-06-01 11:15 PM")) . "\n";
OUTPUT
01 June 2011 11:15:00 PM
Y-m-d hh:mm
will work
echo strtotime('2011-12-14 11:44 am');
cit @Pekka :)
strtotime($month."-".$day."-".$year)
精彩评论