开发者

Javascript to compare two dates, from strings, begin <= end

I get two strings formated like (Brazilian Format): "DD/MM/YYYY", I need to compare both. Since the first field is the begin and the last is the end,

My validation is begin <= e开发者_开发百科nd

Date.new(begin) is generating 'invalid date' even on ISO !


Don't use Date.new. Use new Date(). Because of the format of your date string, I would recommend grabbing each field individually and passing them into the constructor:

var startYear = parseInt(document.getElementById('startYear'), 10);
var startMonth = parseInt(document.getElementById('startMonth'), 10) - 1; // as per Residuum's comment
var startDay = parseInt(document.getElementById('startDay'), 10);
var start = new Date(startYear, startMonth, startDay);

etc. If you're handed a date string, then you can use fuzzy lollipop's method to get each field from the string. I'm not sure if the Date constructor will accept unparsed strings for the individual fields, however.

The, once you have the two dates you'd like to compare, just compare their values in milliseconds since the epoch:

function isValid(start, end) {
    return start.getTime() < end.getTime();
}


There's a nice date handling library called datejs which has a parseExact(dateStr, format) method.


you can do this, if you know your date will always be formatted the same way dd/mm/yyyy

today = "23/02/1001";
dateComponents = today.split("/");
date = new Date(dateComponents[2], dateComponents[1] - 1, dateComponents[0]);

but a better solutions is to look at this page there is Datejs which is a good alternative to date processing.


Quick 'n dirty :

function is_valid (start , end) {
     return start.split('/').reverse().join('') <= end.split('/').reverse().join('') ;
}

That is, split the date into components, reverse the order join them again and do a string comparison.

Edit: As noted in the comment, of course this won't work if your month/days smaller than 10 are not zero padded.


The new 'hotness' in JS time world: http://momentjs.com/ Fits this use-case as well


Here are all available constructors for date objects in Javascript:

dateobject = new Date(); // returns date of current time stamp
                         // on the browser
dateobject = new Date("Month Day, Year Hours:Minutes:Seconds");
dateobject = new Date(Year, Month, Day);
dateobject = new Date(Year, Month, Day, Hours, Minutes, Seconds);
dateobject = new Date(Milliseconds);

Pick the one you try to use, but I would go for new Date(Year, Month, Day); in your case.

EDIT: Note: Monthis zero-based in Javascript, so January 1 2010, will be new Date(2010, 0, 1) and December 31 2011 is new Date(2010, 11, 31).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜