基于字符串创建倒数计时器

时间:2013-12-31 21:01:26

标签: javascript date

我正在制作一个脚本,根据管理员定义的字符串日期和时间创建一个倒数计时器。我已经对它进行了编码,但是,存在用户根据其时区看到不同计时器的问题。例如,如果管理员将日期和时间设置为今天下午4:50(从现在起一小时),他会在01:00:00看到计时器,而我会在04:00:00看到它。显然,我希望计时器能够为每个人显示相同的内容。

有什么想法吗?

以下是代码的一部分:

//stringDate is the date and time string the admin sets
var splitSD = stringDate.split(' ');

    //isolate date, time, notation
    var splitDate = splitSD[0];
    var splitTime = splitSD[1];
    var splitNotation = splitSD[2];

    //isolate month, day, year
    var formatDate = splitDate.split('/');
    formatDate['month'] = formatDate[0];
    formatDate['day'] = formatDate[1];
    formatDate['year'] = formatDate[2];

    //isolate hour, minute, second
    var formatTime = splitTime.split(':');
    formatTime['hour'] = formatTime[0];
    formatTime['minute'] = formatTime[1];
    formatTime['second'] = '00';

    //change hour to 24-hour clock based on notation
    if(splitNotation == 'PM' && parseInt(formatTime['hour'])<12){
        formatTime['hour'] = parseInt(formatTime['hour']) + 12;
    }
    if(splitNotation == 'AM' && parseInt(formatTime['hour'])==12){
        formatTime['hour'] = parseInt(formatTime['hour']) - 12;
    }

    //prepend 0 in case...
    formatDate['month'] = (formatDate['month'].length == 1) ? '0'+formatDate['month'] : formatDate['month'];
    formatDate['day'] = (formatDate['day'].length == 1) ? '0'+formatDate['day'] : formatDate['day'];

    formatTime['hour'] = (formatTime['hour'].length == 1) ? '0'+formatTime['hour'] : formatTime['hour'];
    formatTime['minute'] = (formatTime['minute'].length == 1) ? '0'+formatTime['minute'] : formatTime['minute'];

    //format full date and prevent conversion to local time
    var fullFD = new Date(formatDate['year'] + '-' + formatDate['month'] + '-' + formatDate['day'] + 'T' + formatTime['hour'] + ':' + formatTime['minute'] + ':00-08:00');
    //make timestamp
    var fullFDTimestamp = Math.round(fullFD / 1000);

    return fullFDTimestamp;

1 个答案:

答案 0 :(得分:0)

按要求回答我的评论。

使用Date.prototype&#39; getTimezoneOffset方法。它给出了本地时间与 GMT UTC之间的差异,以分钟为单位。您可以校准倒数计时器以考虑此偏移值并显示所需的时间。