0

I'm trying to get the date 2 weeks before now.

this is my get today in the format I need it function:

function getTodayInFormat()
    {
        var d = new Date();
        var curr_date = d.getDate();
        var curr_month = d.getMonth();
        curr_month++;
        var curr_year = d.getYear()-100;
        return "20" + curr_year + "/" + curr_month + "/" + curr_date ;
    }

Now lets say I do:

var today_date=getTodayInFormat();

How do I get two weeks before this date's date? In the same format? Thank you

Alejandro
  • 1,159
  • 3
  • 16
  • 30

2 Answers2

1

Have you considered the plugin moment.js? I've used it to do things like this in the past and its fantastic and easy to use.

tedwards947
  • 380
  • 1
  • 9
1

Create a function that you can pass a date object to, and subtract two weeks from that date, and return it in whatever format you need.

function two_weeks_ago(date_object) {
    var two_weeks = 1209600000; // two weeks in milliseconds

    var total = date_object.getTime() - two_weeks;
    var date  = new Date(total);

    return date.getFullYear() +'/'+ (date.getMonth() + 1) +'/'+ date.getDate();
}

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • Nice thx and thx for the getFullYear ;) will accept in 5 mins – Alejandro Dec 03 '13 at 20:21
  • @AlejandroCasas - You're welcome, and note that months are zero based in javascript, so december would be 11, and january 0 etc. so you should probably add 1 to the month. It's also generally a good idea to work with date objects and not strings, and add and subtract milliseconds, as that avoids a lot of issues with calculating new months, years etc. when just subtracting 14 days. – adeneo Dec 03 '13 at 20:24