我有两个时间值,从下拉框中选择。时间格式为hh:mm am/pm
。我需要比较这两个日期。我已经完成了这段代码,但它对我不起作用。
<select id="eventstarttime">
<option>10:00am</option>
........
<option>3:00pm</option>
</select>
<select id="eventstoptime" onblur="return checktime()">
<option>10:00am</option>
........
<option>3:00pm</option>
</select>
javascript方法是
function checktime()
{
var start = document.getElementById("eventstarttime").value;
var end = document.getElementById("eventstoptime").value;
if(Date.parse('01/01/2011 '+end) < Date.parse('01/01/2011 '+start))
{
alert("End time should exceed the start time");
}
else if(Date.parse('01/01/2011 '+end) -Date.parse('01/01/2011 '+start)==0)
{
alert("Start time and end time cannot be same");
}
return false;
}
答案 0 :(得分:7)
如果您向value
元素添加24小时option
属性,例如
<select id="eventstarttime">
<option value="1000">10:00am</option>
<option value="1215">12:15pm</option>
<option value="1500">3:00pm</option>
</select>
<select id="eventstoptime" onblur="return checktime()">
<option value="1000">10:00am</option>
<option value="1215">12:15pm</option>
<option value="1500">3:00pm</option>
</select>
您可以使用
轻松比较它们function checktime()
{
var start = document.getElementById("eventstarttime").value;
var end = document.getElementById("eventstoptime").value;
if (end < start)
{
alert("End time should exceed the start time");
}
else if (end == start)
{
alert("Start time and end time cannot be same");
}
return false;
}
无需JavaScript Date
方法。
答案 1 :(得分:3)
您必须将am
和pm
与时间值分开space
。同样在代码中,变量dtEnd
和dtStart
未定义。
在else部分,就像下面一样:
else if(end == start)
{
alert("Start time and end time cannot be same");
}
答案 2 :(得分:1)
尝试strtotime
(http://php.net/manual/en/function.strtotime.php)
$firstTime="10:00 am";
$secondTime="3:00 am";
$result =strtotime ($firstTime) > strtotime($secondime);
答案 3 :(得分:0)
您可以通过PHP执行此操作:
var d1 = "15:30";
var d2 = "15:36";
if (new Date(d1) < new Date(d2)) {alert('newer')}
查看参考URls:
jQuery/JS - How to compare two date/time stamps?
how to get current time and then compare them using jquery
使用PHP,您可以这样做:
$time1 = strtotime("15:30");
$time2 = strtotime("15:40");
if($time1<$time2)
{
echo "time 1 is smaller";
}
else if($time1>$time2)
{
echo "time 2 is smaller";
}
else
{
echo "both are same";
}
希望这会对你有所帮助
答案 4 :(得分:0)
在您的HTML代码中,在选择选项值
中添加'hh:mm'和'am / pm'之间的空格
function checktime()
{
var start = document.getElementById("eventstarttime").value;
var end = document.getElementById("eventstoptime").value;
if(Date.parse('01/01/2011 '+end) < Date.parse('01/01/2011 '+start))
{
alert("End time should exceed the start time");
}
else if(Date.parse('01/01/2011 '+end) -Date.parse('01/01/2011 '+start)==0)
{
alert("Start time and end time cannot be same");
}
return false;
}
<select id="eventstarttime">
<option value='10:00 am'>10:00am</option>
<option value='3:00 pm'>3:00pm</option>
</select>
<select id="eventstoptime" onblur="return checktime()">
<option value='10:00 am'>10:00am</option>
<option value='3:00 pm'>3:00pm</option>
</select>