-2

I am trying to do date comparison in javascript.Through a web service call I am getting a date in the form of ""2014-07-02T09:49:49.299Z" and from database I am getting the dat like "2014-07-11 16:01:34".I need to compare these two dates after doing some kind of formatting.i am not sure how to format these two kind of dates to a common format.

Thanks in advance.....

MobX
  • 2,640
  • 7
  • 33
  • 54

1 Answers1

1

You have date string like : -

 var date = "2014-07-02T09:49:49.299Z"

You can try this:-

var  getDateString = function(date, format) {
        var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
        getPaddedComp = function(comp) {
            return ((parseInt(comp) < 10) ? ('0' + comp) : comp)
        },
        formattedDate = format,
        o = {
            "y+": date.getFullYear(), // year
            "M+": months[date.getMonth()], //month
            "d+": getPaddedComp(date.getDate()), //day
            "h+": getPaddedComp((date.getHours() > 12) ? date.getHours() % 12 : date.getHours()), //hour
            "m+": getPaddedComp(date.getMinutes()), //minute
            "s+": getPaddedComp(date.getSeconds()), //second
            "S+": getPaddedComp(date.getMilliseconds()), //millisecond,
            "t+": (date.getHours() >= 12) ? 'PM' : 'AM'
        };

        for (var k in o) {
            if (new RegExp("(" + k + ")").test(format)) {
                formattedDate = formattedDate.replace(RegExp.$1, o[k]);
            }
        }
        return formattedDate;
    };

Now to format the date, write:-

getDateString(new Date(date), "h:m:s:t")

And to compare two dates try this

var date = "2014-07-02T09:49:49.299Z";
var date1 = "2013-07-02T09:49:49.299Z";
var compareDate = function(date,date1){
if(new Date(date).getTime()>new Date(date1).getTime()){
console.log("greater date");
} else{
console.log("lesser date");
}
}
George
  • 11
  • 2