MM / dd / yyyy格式的特定星期几的javascript日期而不是库

时间:2022-03-26 16:57:57

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:

我知道有很多关于在javascript中找到一周中特定日期的日期的线程,但是所有这些都以如下格式给出:

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.

但我希望以这种格式12/22/2013 - MM / dd / yyyy我也想要最近的星期天和我一直使用的代码不能一直工作。我认为在新月开始时它会搞砸。

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

当我试图从它不起作用的那天减去数字时,所以我不能得到最近的星期日的数据作为MM / dd / yyyy

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

如何在不使用特殊库的情况下获取MM / dd / yyyy最近星期日的日期进行打印?

5 个解决方案

#1


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:

您可以使用.getDay获取当前工作日,返回0(星期日)和6(星期六)之间的数字。所以你要做的就是从日期中减去这个数字:

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:

要获得下周日的日期,您必须计算下一个星期日的天数,即7 - currentTime.getDay()。所以代码变成:

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

#2


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);

#3


1  

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...

要获得上一个星期日,您可以使用while循环减去一天,直到您遇到星期天,就像这样......

  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...

要一起看整个事情,看看我创造的这个DEMO ......

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

**注意:确保在查看演示时打开控制台选项卡。这样你就可以看到输出。

#4


1  

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

您可以在Date上创建原型函数来执行您想要的操作:

    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());

#5


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.

像这样的东西会起作用。这将创建一个可重用的dateHelper对象(您可能会添加日期帮助程序方法,因为您不希望使用现成的库)。获取日期,验证它是日期对象,然后通过减去现在和上一个星期日之间的毫秒数来计算上一个星期日。

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

底部的日志记录显示了未来100天的工作原理。

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));
}

#1


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:

您可以使用.getDay获取当前工作日,返回0(星期日)和6(星期六)之间的数字。所以你要做的就是从日期中减去这个数字:

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:

要获得下周日的日期,您必须计算下一个星期日的天数,即7 - currentTime.getDay()。所以代码变成:

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

#2


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);

#3


1  

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...

要获得上一个星期日,您可以使用while循环减去一天,直到您遇到星期天,就像这样......

  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...

要一起看整个事情,看看我创造的这个DEMO ......

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

**注意:确保在查看演示时打开控制台选项卡。这样你就可以看到输出。

#4


1  

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

您可以在Date上创建原型函数来执行您想要的操作:

    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());

#5


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.

像这样的东西会起作用。这将创建一个可重用的dateHelper对象(您可能会添加日期帮助程序方法,因为您不希望使用现成的库)。获取日期,验证它是日期对象,然后通过减去现在和上一个星期日之间的毫秒数来计算上一个星期日。

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

底部的日志记录显示了未来100天的工作原理。

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));
}