0

I have two datepicker fields (telerik, not jquery UI) and also a radio button list containing buttons for week, month, year, etc.

The user can either select a date range using the two datepickers, or alternatively, they can click one of the radio buttons and the fields should populate based on their choice.

So if the user selects week, the end date should be today and the start date should be 7 days ago.

What I have at the moment is this:

 $(function () {
        $("#dateRange_week").click(function () {
            var now = new Date();
            var startDate = now;
            $("#StartDate").val(startDate);
            $("#EndDate").val(now);
        });
    });

currently the jQuery inserted dates are strings formatted as follows

Tue Oct 02 2012 12:08:01 GMT-0400 (Eastern Daylight Time)
  • How do I calculate startDate as now - 7 days?
  • How can I format the dates as mm/dd/yyyy?

EDIT___

The fix: Using Date.js as per the accepted answer below, the jQuery becomes

        $("#dateRange_week").click(function () {
            var startDate = (7).days().ago();
            var start = startDate.toString("M/d/yyyy");
            var endDate = new Date();
            var end = endDate.toString("M/d/yyyy");
            $("#StartDate").val(start);
            $("#EndDate").val(end);
        });
Forty-Two
  • 7,535
  • 2
  • 37
  • 54

3 Answers3

1

It's a pity, but JS doesn't have good datetime manipulation abilities.
Good news - you can use some plugin for that.
For example:

  • Moment - very good plugin from SO user timrwood
  • date.js - another good plugin for date and time manipulation

They both (and many others) have functions for adding/subtracting days and date formatting. And many other useful options.

Community
  • 1
  • 1
Smileek
  • 2,702
  • 23
  • 26
0

Here is a good start for formatting the jQuery date jQuery date formatting

And this might help for subtracting days Adding/Subtracting days from a date doesn't change the year/month correctly

Community
  • 1
  • 1
MikeB
  • 2,402
  • 1
  • 15
  • 24
0

Try something like:

DateTime dtNow = DateTime.Now;
DateTime dtBegin = DateTime.MinValue;
DateTime dtEnd = DateTime.MinValue;
dtBegin = dtNow.AddDays(1 - Convert.ToDouble(dtNow.DayOfWeek));
dtEnd = dtNow.AddDays(7 - Convert.ToDouble(dtNow.DayOfWeek));

To formate mm/DD/yyyy use .ToShortDateString()

PiLHA
  • 2,326
  • 1
  • 24
  • 32
  • Yes, this function sets the start and end of a week and not necessarily the interval of 7 days. But the method .AddDays() can do this. – PiLHA Oct 02 '12 at 16:35
  • My question is about inserting and manipulating the dates via jQuery. – Forty-Two Oct 02 '12 at 17:45