最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Compare Date & Time Javascript - Stack Overflow

programmeradmin2浏览0评论

Ok I cant get my head round this, ive looked at so many posts on SF but cant figure it out.

I need to pare two dates & times, start and end. If end is great then alert();

Works in Chrome but not IE(9) (format is: 01-Jan-2013 10:00)

var stDate = new Date(date +" "+ start);
var enDate = new Date(dateEnd + " "+ end);

        if ( Date.parse ( enDate ) > Date.parse ( stDate ) ) {
            alert('on no');
        }

Please help, im stuck...

Ok I cant get my head round this, ive looked at so many posts on SF but cant figure it out.

I need to pare two dates & times, start and end. If end is great then alert();

Works in Chrome but not IE(9) (format is: 01-Jan-2013 10:00)

var stDate = new Date(date +" "+ start);
var enDate = new Date(dateEnd + " "+ end);

        if ( Date.parse ( enDate ) > Date.parse ( stDate ) ) {
            alert('on no');
        }

Please help, im stuck...

Share Improve this question asked Jan 11, 2013 at 20:51 D-WD-W 5,35116 gold badges48 silver badges75 bronze badges 2
  • 1 You should check out moment.js. It handles all the cross-browser Date fuss for you! – Casey Foster Commented Jan 11, 2013 at 20:54
  • i'm wondering if the Timezones have anything to do with this? – jdavid Commented Jan 11, 2013 at 21:07
Add a ment  | 

3 Answers 3

Reset to default 3

Just make a custom parser, it's done faster than trying to figure how different browsers treat various time string formats:

function parse(datestring){
    var months = {"Jan":0,"Feb":1,"Mar":2,"Apr":3,"May":4,"Jun":5,"Jul":6,"Aug":7,"Sep":8,"Oct":9,"Nov":10,"Dec":11}
    var timearray = datestring.split(/[\-\ \:]/g)
    return Date.UTC(timearray[2],months[timearray[1]],timearray[0],timearray[3],timearray[4])
}

This returns Unix time in milliseconds, and it use UTC, thus avoiding plications from the missing hour of daylight savings time. It works with the format you specified, but does not validate input.

if ( enDate.getTime() > stDate.getTime() ) {
    alert('oh no');
}

Pushing to number (+enDate) is the same as using the .getTime() method:

if ( +enDate > +stDate ) {
    alert('oh no');
}
var stDate = new Date(date +" "+ start);
var enDate = new Date(dateEnd + " "+ end);

        if ( enDate.getTime() > stDate.getTime() ) {
            alert('on no');
        }

To create a Date object:

var d = new Date();
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);

getTime() Return the number of milliseconds since 1970/01/01

发布评论

评论列表(0)

  1. 暂无评论