如何添加15分钟自定义计时器 - Javascript

时间:2010-10-25 11:06:13

标签: javascript jquery jquery-ui

我有这个js:

<script>
$('#appt_start').val(parent.location.hash);
$('#appt_end').val(parent.location.hash);
</script>
例如,

从url something.com/diary.php#0800中获取哈希值。

然后,该值用于在约会表单中自动填充开始和结束时间。

我需要第二次(#appt_end)增加15分钟?任何想法我是如何做到的,我的js是垃圾......

谢谢!

修改

这是我正在使用的工作代码:

// add the time into the form
var hashraw = parent.location.hash;
var minIncrement = 15; // how many minutes to increase

hash = hashraw.replace("#", ""); // remove the hash

// first we split the time in hours and mins
var hours = parseInt(hash.substring(0, 2),10); // get hours (first 2 chars)
var mins = parseInt(hash.substring(2, 4),10); // get mins (last 2 chars)

// add the new minutes, and enforce it to fit 60 min hours 
var newMins = (mins + minIncrement )%60; 
// check if the added mins changed thehour 
var newHours = Math.floor( (mins + minIncrement ) / 60 );

// create the new time string (check if hours exceed 24 and restart it
// first we create the hour string
var endTime = ('0' + ((hours+newHours)%24).toString()).substr(-2);
// then we add the min string
endTime += ('0'+ newMins.toString()).substr(-2);

$('#appt_start').val(hash);
$('#appt_end').val( endTime );

3 个答案:

答案 0 :(得分:3)

您需要以小时/分钟为单位分割时间,然后对其应用时间逻辑以增加它...

var hash = parent.location.hash.replace('#','');
var minIncrement = 15; // how many minutes to increase

// first we split the time in hours and mins
var hours = parseInt(hash.substring(0, 2),10); // get hours (first 2 chars)
var mins = parseInt(hash.substring(2, 4),10); // get mins (last 2 chars)

// add the new minutes, and enforce it to fit 60 min hours 
var newMins = (mins + minIncrement )%60; 
// check if the added mins changed thehour 
var newHours = Math.floor( (mins + minIncrement ) / 60 );

// create the new time string (check if hours exceed 24 and restart it
// first we create the hour string
var endTime = ('0' + ((hours+newHours)%24).toString()).substr(-2);
// then we add the min string
endTime += ('0'+ newMins.toString()).substr(-2);

$('#appt_start').val( hash );
$('#appt_end').val( endTime );

http://www.jsfiddle.net/gaby/cnnBc/

上查看

答案 1 :(得分:1)

试试这个:

    <script>
        $(function() {
$('#appt_start').val(parent.location.hash);
var end = parent.location.hash;
end = end.replace("#", "");
end = (end * 1) + 15;
if (end < 1000) {end = '0' + end};
$('#appt_end').val(end);
});
</script>

答案 2 :(得分:0)

这样可能吗?

Working Demo

var hash="08:00";
$('#appt_start').val(hash);

var d = new Date("October 13, 1975 "+hash) 
d.setMinutes(d.getMinutes()+15);

$('#appt_end').val(d.getHours()+":"+d.getMinutes());

您使用虚构日期以便将分钟相加。 如果哈希没有“:”,则可以使用子字符串插入“:”。