简体   繁体   中英

jQuery: Add 4 weeks to date in format dd-mm-yyyy

I have a string which has a date in the format: dd-mm-yyyy

How I can add 4 weeks to the string and then generate a new string using jQuery / Javascript?

I have

var d = new Date(current_date); 
d.setMonth(d.getMonth() + 1); 
current_date_new = (d.getMonth() + 1 ) + '-' + d.getDate() + '-' + d.getFullYear();    
alert(current_date_new); 

but it complains that the string provided is in the incorrect format

EDIT: After a bit of fiddling , here's the solution:

First, split the string to individual parts.

var inputString = "12-2-2005";
var dString = inputString.split('-');

Then, parse the string to a datetime object and add 28 days (4 weeks) to it.

var dt = new Date(dString[2],dString[1]-1,dString[0]);
dt.setDate(dt.getDate()+28);

Finally, you can output the date

var finalDate = dt.GetDate() + "-" + (dt.GetMonth()+1) + "-" + dt.GetYear();

This code should return 12-3-2005 .

CAVEATS: It seems JavaScript's Date object takes 0-11 as the month field, hence the -1 and +1 to the month in the code.

EDIT2: To do padding, use this function:

function pad(number, length) {

    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }

    return str;

}

and change your output to

var finalDate = pad(dt.GetDate(),2) + "-" + pad(dt.GetMonth()+1,2) + "-" + dt.GetYear();

Check the updated fiddle.

There is no need to convert to mm-dd-yyyy, simple split string by the minus sign and create new Date object with the following code:

var string = '12-02-2012';
var split = string.split('-');
var date = Date(split[2],parseInt(split[1])-1,parseInt(split[0])+1)

date.setDate(date.getDate() + 28);
var fourWeeksLater = date.getDay() + "-"+date.getMonth() +"-"+date.getYear();

This should be working:

var formattedDate = '01-01-2012',
    dateTokens = formattedDate.split('-'),
    dt = new Date(dateTokens[2], parseInt( dateTokens[1], 10 ) - 1, dateTokens[0]), // months are 0 based, so need to add 1
    inFourWeeks = new Date( dt.getTime() + 28 * 24 * 60 * 60 * 1000 );

jsfiddle: http://jsfiddle.net/uKDJP/

Edit:

Using Globalize you can format inFourWeeks:

Globalize.format( inFourWeeks, 'dd-MM-yyyy' ) // outputs 29-01-2012

Instead of writing your own parser for dates, I would use moment.js .

To parse your date:

var date = moment('14-06-2012', 'DD-MM-YYYY');

To add 4 weeks to it:

date.add('weeks', 4);

Or in one go:

var date = moment('14-06-2012', 'DD-MM-YYYY').add('weeks', 4);

And convert it to string:

var dateString = date.format('DD-MM-YYYY');

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