JavaScript如何以dd-mm-yy格式获取明天的日期


90

我正在尝试使JavaScript以(dd-mm-yyyy)格式显示明天的日期

我有这个脚本,它以(dd-mm-yyyy)格式显示今天的日期。

var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
document.write("<b>" + day + "/" + month + "/" + year + "</b>")

Displays: 25/2/2012 (todays date of this post)

但是我如何以相同的格式显示明天的日期,即 26/2/2012

我尝试了这个:

var day = currentDate.getDate() + 1

但是我可以保留+1并超过31个,显然一个月中没有超过32天

一直在搜寻数小时,但似乎无法解决这个问题?

Answers:


176

这应该修复它对您来说真的很不错。

如果您传递Date构造函数一段时间,它将完成其余工作。

24小时60分钟60秒1000毫秒

var currentDate = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
document.write("<b>" + day + "/" + month + "/" + year + "</b>")

要记住的一件事是,此方法将返回从现在开始24小时的日期,这在夏令时前后可能不准确。

菲尔的答案工作随时随地:

var currentDate = new Date();
currentDate.setDate(currentDate.getDate() + 1);

我编辑帖子的原因是因为我自己创建了一个错误,该错误在DST期间使用旧方法曝光。


9
谢谢,简短一点var currentDate = new Date(+new Date() + 86400000);
Ikrom 2014年

13
请注意,使用这种策略可能会在DST周围遇到问题,这会导致一年中的一天有23个小时,有一天有25个小时。下面Phil的回答避免了这个问题。
gsf

3
new Date().getTime()可以简化为Date.now()
czerny

它们都正确,但是我不认为IE8具有Date.now()。
Roderick Obrist

2
@ ConorB,.getMonth()对于1月返回0,对于2月返回1 ...对于12月返回11。加1会将其从数组索引转换为可读日期。
Roderick Obrist

135

JavaScriptDate类为您处理此问题

var d = new Date("2012-02-29")
console.log(d)
// Wed Feb 29 2012 11:00:00 GMT+1100 (EST)

d.setDate(d.getDate() + 1)
console.log(d)
// Thu Mar 01 2012 11:00:00 GMT+1100 (EST)

console.log(d.getDate())
// 1

如果今天是一个月的最后一天(例如31日),这是否仍然有效?如果加上+1,结果不是32位吗?
Timo'Apr

19
@Timo可以肯定,我的例子恰好证明了这一点
Phil

1
哦,是的,你是对的。我忘了2月只有28天:-)
Timo 2015年

这对我今天失败了,因为新的Date('2016-10-31')返回了'Sun Oct 30 2016 23:00:00 GMT-0100(AZOT)'。我在亚速尔群岛,时区从AZOST更改为AZOT
nunoarruda

@nunoarruda对不起,不太确定您在说什么或与这个答案有什么关系
Phil

7

我将使用DateJS库。它可以做到这一点。

http://www.datejs.com/

请执行以下操作:

var d = new Date.today().addDays(1).toString("dd-mm-yyyy");

Date.today() -今天午夜给你。


1
我更喜欢Phil的答案……我在所有日期中都使用DateJS-但似乎可以单独使用JS来完成!
MattW'2

4
Date.parse('明天').toString('dd-MM-yyyy');
geoffrey.mcgill 2012年

5

Date.prototype.setDate()方法甚至接受标准范围之外的参数,并相应地更改日期。

function getTomorrow() {
    const tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1); // even 32 is acceptable
    return `${tomorrow.getFullYear()}/${tomorrow.getMonth() + 1}/${tomorrow.getDate()}`;
}

4

下面结合了Roderick和Phil的答案以及两个额外的条件(占月数/天的单位)。

我使用过的许多API对此都比较挑剔,并且要求日期具有八位数字(例如'02022017'),而不是在某些情况下date类将为您提供的六位数或七位数。

function nextDayDate() {
      // get today's date then add one
      var nextDay = new Date();
      nextDay.setDate(nextDay.getDate() + 1);

      var month = nextDay.getMonth() + 1;
      var day = nextDay.getDate();
      var year = nextDay.getFullYear();

      if (month < 10) { month = "0" + month } 
      if (day < 10) { day = "0" + day }

      return month + day + year;
}

3

用例 :

Date.tomorrow() // 1 day next 
Date.daysNext(1) // alternative Date.tomorrow()
Date.daysNext(2) // 2 days next. 

如果“明天”不依赖于今天,而是依赖于另一个不同的日期Date.now(),请不要使用静态方法,而必须使用非静态方法:

即:2008年12月5日星期五

 var dec5_2008=new Date(Date.parse('2008/12/05'));
 dec5_2008.tomorrow(); // 2008/12/06
    dec5_2008.tomorrow().day // 6
    dec5_2008.tomorrow().month // 12
    dec5_2008.tomorrow().year //2008
 dec5_2008.daysNext(1); // the same as previous
 dec5_2008.daysNext(7) // next week :)

API:

Dateold=Date;function Date(e){var t=null;if(e){t=new Dateold(e)}else{t=new Dateold}t.day=t.getDate();t.month=t.getMonth()+1;t.year=t.getFullYear();return t}Date.prototype.daysNext=function(e){if(!e){e=0}return new Date(this.getTime()+24*60*60*1e3*e)};Date.prototype.daysAgo=function(e){if(!e){e=0}return Date.daysNext(-1*e)};Date.prototype.tomorrow=function(){return this.daysNext(1)};Date.prototype.yesterday=function(){return this.daysAgo(1)};Date.tomorrow=function(){return Date.daysNext(1)};Date.yesterday=function(){return Date.daysAgo(1)};Date.daysNext=function(e){if(!e){e=0}return new Date((new Date).getTime()+24*60*60*1e3*e)};Date.daysAgo=function(e){if(!e){e=0}return Date.daysNext(-1*e)}

3

方法1:如果您在使用其他库时没有问题,则可以使用moment.js进行工作

moment().add('days', 1).format('L');

方法2:使用Date.js,

<script type="text/javascript" src="date.js"></script>    
var tomorrow = new Date.today().addDays(1).toString("dd-mm-yyyy"); 

此方法使用外部库,而不使用本机日期库。由于我的bootstrap-datetimepicker使用的是moment.js和本机日期库,因此我首选方法1。此问题提到了这些方法和其他方法。


2

它非常简单:

1:使用今天的日期和时间创建日期对象。2:使用日期对象方法检索日,月和整年,并使用+运算符将它们连接起来。

访问http://www.thesstech.com/javascript/date-time JavaScript,以获取有关日期和时间的详细教程。

样例代码:

  var my_date = new Date();  
  var tomorrow_date =       (my_date .getDate()+1)  + "-" + (my_date .getMonth()+1) + "-" + my_date .getFullYear();
  document.write(tomorrow_date);

正如OP已经观察到的那样,这不会将日期滚动到月份。
Wolfgang Kuehn,

0
function getMonday(d)
{
   // var day = d.getDay();
   var day = @Config.WeekStartOn
   diff = d.getDate() - day + (day == 0 ? -6 : 0);
   return new Date(d.setDate(diff));
}

0

与原始答案相同,但在一行中:

var tomorrow = new Date(Date.now() + 24 * 60 * 60 * 1000)

数字代表24小时60分钟60秒1000毫秒。


1
由于未考虑DST,因此此答案不正确。
令人失望的

0

您可以尝试以下方法:

function Tomorrow(date=false) {
    var givendate = (date!=false) ? new Date(date) : new Date();
    givendate.setDate(givendate.getDate() + 1);
    var day = givendate.getUTCDate()
    var month = givendate.getUTCMonth()+1
    var year = givendate.getUTCFullYear()
    result ="<b>" + day + "/" + month + "/" + year + "</b>";
    return result;
} 
var day = Tomorrow('2020-06-30');
console.log('tomorrows1: '+Tomorrow('2020-06-30'));
console.log('tomorrows2: '+Tomorrow());


0
        Date.prototype.NextDay = function (e) {
        return new Date(this.getFullYear(), this.getMonth(), this.getDate() + ("string" == typeof e ? parseInt(e, 10) : e));
    }

    // tomorrow
    console.log(new Date().NextDay(1))

    // day after tomorrow
    console.log(new Date().NextDay(2))

0

仅使用JS(纯js)

今天

new Date()
//Tue Oct 06 2020 12:34:29 GMT+0530 (India Standard Time)
new Date(new Date().setHours(0, 0, 0, 0))
//Tue Oct 06 2020 00:00:00 GMT+0530 (India Standard Time)
new Date(new Date().setHours(0, 0, 0,0)).toLocaleDateString('fr-CA')
//"2020-10-06"

明天

new Date(+new Date() + 86400000);
//Wed Oct 07 2020 12:44:02 GMT+0530 (India Standard Time)
new Date(+new Date().setHours(0, 0, 0, 0) + 86400000);
//Wed Oct 07 2020 00:00:00 GMT+0530 (India Standard Time)
new Date(+new Date().setHours(0, 0, 0,0)+ 86400000).toLocaleDateString('fr-CA')
//"2020-10-07"
//don't forget the '+' before new Date()

后天

只需乘以两个ex:-2 * 86400000

您可以从https://stackoverflow.com/a/3191729/7877099找到所有语言环境的短代码


-1
        //-----------Date Configuration march 18,2014----------------------

        //alert(DateFilter);

        var date = new Date();
        y = date.getFullYear(), m = date.getMonth();
        var EndDate = new Date();



        switch (DateFilter) {
            case 'today': var StartDate = EndDate;   //todays date                 
                break;
            case 'yesterday':
                var d = new Date();
                var previousDate = new Date(d.getTime() - 1000 * 60 * 60 * 24);
                var StartDate = new Date(previousDate.yyyymmdd()); //yesterday Date
                break;
            case 'tomorrow':
                var d = new Date();
                var NextDate = new Date(d.getTime() + 1000 * 60 * 60 * 24);
                var StartDate = new Date(NextDate.yyyymmdd()); //tomorrow Date
                break;
            case 'thisweek': var StartDate = getMonday(new Date()); //1st date of this week
                break;
            case 'thismonth': var StartDate = new Date(y, m, 1);  //1st date of this month
                break;
            case 'thisyear': var StartDate = new Date("01/01/" + date.getFullYear());  //1st date of this year
                break;
            case 'custom': //var StartDate = $("#txtFromDate").val();                   
                break;
            default:
                var d = new Date();
                var StartDate = new Date(d.getTime() - 30 * 24 * 60 * 60 * 1000); //one month ago date from now.
        }


        if (DateFilter != "custom") {
            var SDate = $.datepicker.formatDate('@Config.DateFormat', StartDate); $("#txtFromDate").val(SDate);
            var EDate = $.datepicker.formatDate('@Config.DateFormat', EndDate); $("#txtToDate").val(EDate);
        }
        //-----------Date Configuration march 18,2014----------------------

请考虑在您的答案中添加解释。
2014年

-1
var curDate = new Date().toLocaleString().split(',')[0];

只是!格式为dd.mm.yyyy。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.