Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript date of specific day of the week in MM/dd/yyyy format not libraries

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?

like image 670
user2330624 Avatar asked Dec 23 '13 21:12

user2330624


1 Answers

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()));
like image 76
Felix Kling Avatar answered Sep 25 '22 23:09

Felix Kling