Rupesh Nerkar
Rupesh Nerkar

Reputation: 391

how to compare date which is given by user to date in javascript..?

In my web-site I am getting a date from user which in format like "dd-mm-yyyy",now I want to get the date which is 7-day before of that user's date. I am able to get the current date in format "dd-mm-yyyy" but how would I know the date which is one week before user's date in javascript?

Upvotes: 0

Views: 251

Answers (5)

Shiridish
Shiridish

Reputation: 4962

Try this--

 var MyDate = new Date('11/30/2012');  //date format in mm/dd/yyyy
 MyDate.setDate(MyDate.getDate() -7)
 var newDate = MyDate.getMonth()+1 + '/' + MyDate.getDate() + '/' +    MyDate.getFullYear()
 alert(newDate);

Note- subtracting seven days to a date shifts the month or year and the changes are handled automatically by the Date object.

Upvotes: 0

RobG
RobG

Reputation: 147413

You can convert a date string in the format dd-mm-yyyy to a date object using:

function toDate(d) {
    d = d.split('-');
    return new Date(d[2], --d[1], d[0]);
}

Then use Osiris' answer to add or subtract 7 days.

Upvotes: 0

sachinNadgouda
sachinNadgouda

Reputation: 56

Set Dates

We can easily manipulate the date by using the methods available for the Date object.

In the example below we set a Date object to a specific date (14th January 2010):

var myDate=new Date();

myDate.setFullYear(2010,0,14);

And in the following example we set a Date object to be 7 days in past:

var myDate=new Date(); //or users date

// myDate will be users current date

myDate.setDate(myDate.getDate()-7);

//now substract 7 days to get the date u want.

Follow the following link

http://www.w3schools.com/js/js_obj_date.asp

Or follow this

http://www.techrepublic.com/article/manipulate-time-and-date-values-with-javascripts-date-object/6076869

Upvotes: 0

Sap
Sap

Reputation: 5301

Why don't you use datejs, it's the best date related js library I have seen. Chcek the documentation here. http://code.google.com/p/datejs/wiki/APIDocumentation

Search for add method

Upvotes: 0

Osiris
Osiris

Reputation: 4185

If you already have a Date object, use yourDate.setDate(yourDate.getDate() - 7 );

Upvotes: 1

Related Questions