简体   繁体   中英

How can I compare two dates in format dd mmm yyyy?

I would like to compare two dates in this format dd mmm yyyy, compare validators wont work because of the format and custom validator is server side validation. I would like to have a clinet side validation. What would be the best way to do it? if you have any examples or links please let me know.

I dont know if there are options availables with ajax, jquery or javascript that can do this?

Cheers

Since JavaScript natively converts from MMM dd, yyyy , this would be one approach:

var date1Str = "09 Sep 2011";
var date2Str = "04 May 2012";

var dateParts = date1Str.split(" ");
var newDateStr = dateParts[1] + " " + dateParts[0] + ", "  + dateParts[2];
var date1 = new Date( newDateStr );

var dateParts = date2Str.split(" ");
var newDateStr = dateParts[1] + " " + dateParts[0] + ", "  + dateParts[2];
var date2 = new Date( newDateStr );

if ( date1 > date2 )
    ...

There are tons of links on the net to do date parsing in JavaScript and plenty of libraries that make it easier. Remember that culture plays a part. "Oct" is in English but in German it will be "Okt".

Here's a simple class you can use to compare dates; the convert function has been adjusted to accommodate your format:

<script type="text/javascript">
    var dates = {
        convert:function(d) {
            return (
                d.constructor === Date ? d :
                d.constructor === Array ? new Date(d[1],d[0],d[2]) :
                d.constructor === Number ? new Date(d) :
                d.constructor === String ? new Date(d) :
                typeof d === "object" ? new Date(d.year,d.month,d.date) :
                NaN
            );
        },
        compare:function(a,b) {
            return (
                isFinite(a=this.convert(a).valueOf()) &&
                isFinite(b=this.convert(b).valueOf()) ?
                (a>b)-(a<b) :
                NaN
            );
        },
        inRange:function(d,start,end) {
           return (
                isFinite(d=this.convert(d).valueOf()) &&
                isFinite(start=this.convert(start).valueOf()) &&
                isFinite(end=this.convert(end).valueOf()) ?
                start <= d && d <= end :
                NaN
            );
        }
    }
</script>

Credit for this class belongs to @some: https://stackoverflow.com/a/497790/879420

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM