6

I know there are a lot of threads about finding the date of a specific day of the week in javascript but the all give it in the format like so:

Sun Dec 22 2013 16:39:49 GMT-0500 (EST)

but I would like it in this format 12/22/2013 -- MM/dd/yyyy Also I want the most recent Sunday and the code I have been using does not work all the time. I think during the start of a new month it screws up.

function getMonday(d) {
d = new Date(d);
var day = d.getDay(),
    diff = d.getDate() - day + (day == 0 ? -6:0); // adjust when day is sunday
return new Date(d.setDate(diff));
}

I have code that gives me the correct format but that is of the current date:

var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
document.write(month + "/" + day + "/" + year)

this prints:

>>> 12/23/2013

when I try to subtract numbers from the day it does not work, so I cannot get the dat of the most recent Sunday as MM/dd/yyyy

How do I get the date of the most recent sunday in MM/dd/yyyy to print, without using special libraries?

user2330624
  • 303
  • 1
  • 7
  • 16

5 Answers5

4

You can get the current weekday with .getDay, which returns a number between 0 (Sunday) and 6 (Saturday). So all you have to do is subtract that number from the date:

currentTime.setDate(currentTime.getDate() - currentTime.getDay());

Complete example:

var currentTime = new Date()
currentTime.setDate(currentTime.getDate() - currentTime.getDay());
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
console.log(month + "/" + day + "/" + year)
// 12/22/2013 

To set the date to any other previous weekday, you have to compute the number of days to subtract explicitly:

function setToPreviousWeekday(date, weekday) {
    var current_weekday = date.getDay();
    // >= always gives you the previous day of the week
    // > gives you the previous day of the week unless the current is that day
    if (current_weekday >= weekday) {
        current_weekday += 6;
    }
    date.setDate(date.getDate() - (current_weekday - weekday));
}

To get the date of next Sunday you have to compute the number of days to the next Sunday, which is 7 - currentTime.getDay(). So the code becomes:

currentTime.setDate(currentTime.getDate() + (7 -  currentTime.getDay()));
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • does "var currentTime = new Date() currentTime.setDate(currentTime.getDate() - currentTime.getDay()); var month = currentTime.getMonth() + 1 var day = currentTime.getDate() var year = currentTime.getFullYear() console.log(month + "/" + day + "/" + year)" always give you the correct date of sunday? it does not screw up when it is a new month? – user2330624 Dec 23 '13 at 22:07
  • From the [documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate): *"If the `dayValue` is outside of the range of date values for the month, `setDate` will update the `Date` object accordingly. For example, if 0 is provided for `dayValue`, the date will be set to the last day of the previous month."* -- so yes. – Felix Kling Dec 23 '13 at 22:09
  • For the next weeks sunday, how would it be obtained? you do not simply add 6 because that will cause problem towards the end of a month? EDIT: I think the above answers this – user2330624 Dec 23 '13 at 22:15
  • No, you have to add `7 - current_time.getDay()`. And yes, `setDate` will *always* make sure you end of up with a valid date. – Felix Kling Dec 23 '13 at 22:24
  • Just relized this does not do mm/dd/yyyy because for next weeks Sunday it does 1/5/2014 not 01/05/2014 – user2330624 Dec 29 '13 at 17:52
  • @user2330624: Well, those methods return *numbers*. But you can easily format them as strings with 0-padding: http://stackoverflow.com/q/1267283/218196 – Felix Kling Dec 29 '13 at 19:29
  • I was using this to find the current value of the the key which is the date so I just changed the key to the same format – user2330624 Dec 29 '13 at 19:45
2

Subtract days like this

// calculate days to subtract as per your need
var dateOffset = (24*60*60*1000) * 5; //5 days
var date = new Date();
date.setTime(date.getTime() - dateOffset);

var day = date.getDate() // prints 19
var month = date.getMonth() + 1
var year = date.getFullYear()
document.write(month + '/' + day + '/' + year);
Raunak Kathuria
  • 3,185
  • 1
  • 18
  • 27
2

Here is my suggestion. Create a function like so... in order to format any date you send it.

function formatDate(myDate) {
var tmp = myDate;
var month = tmp.getMonth() + 1;
var day = tmp.getDate();
var year = tmp.getFullYear();
return (month + "/" + day + "/" + year);
}

Now, to print the current date, you can use this code here:

   var today = new Date();
   var todayFormatted = formatDate(today);

To get the previous Sunday, you can use a while loop to subtract a day until you hit a Sunday, like this...

  var prevSunday = today;
  while (prevSunday.getDay() !== 0) {
    prevSunday.setDate(prevSunday.getDate()-1);
  }

  var sundayFormatted = formatDate(prevSunday);

To see the whole thing together, take a look at this DEMO I've created...

** Note: Make sure you turn on the Console tab when viewing the demo. This way you can see the output.

Charlie74
  • 2,883
  • 15
  • 23
1

You can create prototype functions on Date to do what you want:

    Date.prototype.addDays = function (days) {
        var d = new Date(this.valueOf());
        d.setDate(d.getDate() + days);
        return d;
    }

    Date.prototype.getMostRecentPastSunday = function () {
        var d = new Date(this.valueOf());
        return d.addDays(-d.getDay()); //Sunday is zero
    }

    Date.prototype.formatDate = function () {
        var d = new Date(this.valueOf());
        //format as you see fit
        //http://www.webdevelopersnotes.com/tips/html/10_ways_to_format_time_and_date_using_javascript.php3
        //using your approach...
        var month = d.getMonth() + 1
        var day = d.getDate()
        var year = d.getFullYear()
        return month + "/" + day + "/" + year;
    }

    console.log((new Date()).getMostRecentPastSunday().formatDate());
    console.log((new Date("1/3/2014")).getMostRecentPastSunday().formatDate());

    //or...
    var d = new Date(); //whatever date you want...
    console.log(d.getMostRecentPastSunday().formatDate());
iii
  • 383
  • 1
  • 11
0

Something like this will work. This creates a reusable dateHelper object (you will presumably be adding date helper methods since you don't want to use a library off the shelf). Takes in a date, validates that it is a date object, then calculates the previous Sunday by subtracting the number of millis between now and the previous Sunday.

The logging at the bottom shows you how this works for 100 days into the future.

var dateHelper = {
    getPreviousSunday: function (date) {
        var millisInADay = 86400000;
        if (!date.getDate()) {
            console.log("not a date: " + date);
            return null;
        }
        date.setMilliseconds(date.getMilliseconds() - date.getDay() * millisInADay);
        return date.getMonth() + 1 + "/" + date.getDate() + "/" + date.getFullYear();
   }
}

var newDate = new Date();
console.log(dateHelper.getPreviousSunday(newDate));
var now = newDate.getTime();
for (var i=1; i<100; i++) {
    var nextDate = new Date(now + i * 86400000);
    console.log("Date: + " nextDate + " - previous sunday: " + dateHelper.getPreviousSunday(nextDate));
}
pherris
  • 17,195
  • 8
  • 42
  • 58