根据一天中的时间加载不同的链接

时间:2012-08-31 22:38:12

标签: javascript function datetime

我需要你的帮助。在搜索到处后,我无法找到我需要的正确答案。我正在尝试创建一个javascript函数来根据一天中的时间更改链接href值。 (即我希望链接将用户连接到我们的服务台,以便在晚上11点45分停用,并在上午7点cst激活。)我在网上发现了一个老功能,它可以让它工作,但它有一个开始日期,我是javascript的新手所以我不知道如何将它改为只使用一天的时间。所以,如果你可以请看看代码并建议如何修改它,使它只适用于当天或者可能提供另一种选择我会 欣赏它!

<script type="text/javascript">
var startDay = 5; // Start Day: 0 - 6 (Sun = 0, Mon = 1 ... Fri = 5, Sat = 6)
var startHour = 16; // Start Hour: 0 - 23
var startMin = 8; // Start Min: 0 - 59
var endDay = 5; // End Day: 0 - 6 (Sun = 0, Mon = 1 ... Fri = 5, Sat = 6)
var endHour = 16; // End Hour: 0 - 23
var endMin = 10; // End Min: 0 - 59

function alternateLink(linkObj)
{
var startTimeDate = new Date(2012, 01, 01, startHour, startMin, 00);
with (startTimeDate) while (getDay() != startDay) setDate(getDate()+1);
var startTimeDateMsecs = startTimeDate.getTime();

var endTimeDate = new Date(2012, 01, 01, endHour, endMin-1, 00);
with (endTimeDate) while (getDate() < startTimeDate.getDate()) setDate(getDate()+1);
with (endTimeDate) while (getDay() != endDay) setDate(getDate()+1);
var endTimeDateMsecs = endTimeDate.getTime();

var now = new Date();
var currentTimeDate = new Date(2012, 01, 01, now.getHours(), now.getMinutes(), 00);
with (currentTimeDate) while (getDate()<startTimeDate.getDate()) setDate(getDate()+1); 
with (currentTimeDate) while (getDay() != now.getDay()) setDate(getDate()+1);
var currentTimeDateMsecs = currentTimeDate.getTime();

if (currentTimeDateMsecs >= startTimeDateMsecs && currentTimeDateMsecs <=endTimeDateMsecs) linkObj.href = 'contactus.php';} 
</script>    


<img src="default.png" alt="Time Image" id="image_id">

1 个答案:

答案 0 :(得分:0)

使用getDategetMonthgetFullYear函数:

var now = new Date();
var month = now.getMonth()+1; //return range is 0-11, so add 1
var day = now.getDate();
var year = now.getFullYear();

var startTimeDate = new Date(year, month, day, startHour, startMin, 00);
...
var startTimeDateMsecs = startTimeDate.getTime();

var endTimeDate = new Date(year, month, day, endHour, endMin-1, 00);
...
var endTimeDateMsecs = endTimeDate.getTime();

var currentTimeDateMsecs = now.getTime();

if (currentTimeDateMsecs >= startTimeDateMsecs && currentTimeDateMsecs <=endTimeDateMsecs) 
    linkObj.href = 'contactus.php';
else
    linkObj.href = '#';