javascript:如何将日期字符串(YYYY-MM-DD)增加1天 [英] javascript: how can I increment a date string (YYYY-MM-DD) by 1 day

查看:434
本文介绍了javascript:如何将日期字符串(YYYY-MM-DD)增加1天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何在php中使用date()和mktime()函数,但不知道如何在javascript中完成同样的事情...

I know how to do this in php with date() and mktime() functions, but have no idea how to accomplish the same thing in javascript...

function incr_date(date_str){
    //...magic here
    return next_date_str;
}

var date_str = '2011-02-28';
console.log( incr_date(date_str) ); //want to output "2011-03-01"

这对js来说甚至可能吗?

is this even possible with js?

推荐答案

首先解析它,然后使用 dt.setDate(dt.getDate()+ 1)。但是,您必须手动解析它,或使用 DateJS 或类似内容;所有主流浏览器尚不支持该格式(新日期(date_str) 无效可靠地跨浏览器;请参阅下面的注释。然后将其转换回您的格式。

First you parse it, then you use dt.setDate(dt.getDate() + 1). You'll have to parse it manually, though, or using DateJS or similar; that format is not yet supported across all major browsers (new Date(date_str) will not work reliably cross-browser; see note below). And then convert it back to your format.

以下内容:

function incr_date(date_str){
  var parts = date_str.split("-");
  var dt = new Date(
    parseInt(parts[0], 10),      // year
    parseInt(parts[1], 10) - 1,  // month (starts with 0)
    parseInt(parts[2], 10)       // date
  );
  dt.setDate(dt.getDate() + 1);
  parts[0] = "" + dt.getFullYear();
  parts[1] = "" + (dt.getMonth() + 1);
  if (parts[1].length < 2) {
    parts[1] = "0" + parts[1];
  }
  parts[2] = "" + dt.getDate();
  if (parts[2].length < 2) {
    parts[2] = "0" + parts[2];
  }
  return parts.join("-");
}

实例

请注意 setDate 将正确处理滚动到下一个月份(如有必要,则为年份)。

Note that setDate will correctly handle rolling over to the next month (and year if necessary).

实例

以上测试适用于IE6,IE7,IE8; Linux上的Chrome,Opera和Firefox; Windows上的Chrome,Opera,Firefox和Safari。

The above is tested and works on IE6, IE7, IE8; Chrome, Opera, and Firefox on Linux; Chrome, Opera, Firefox, and Safari on Windows.

关于在JavaScript中支持此格式的说明:新日期(字符串)构造函数最近才具有可接受标准化的格式,如 ECMAScript第5版于2009年12月发布。当浏览器支持时,您的格式将得到支持,但截至本文撰写时,IE的发布版本(甚至IE8)都不支持它。其他最近的浏览器大多数都是这样做的。

A note about support for this format in JavaScript: The new Date(string) constructor in JavaScript only recently had the formats that it would accept standardized, as of ECMAScript 5th edition released in December 2009. Your format will be supported when browsers support it, but as of this writing, no released version of IE (not even IE8) supports it. Other recent browsers mostly do.

这篇关于javascript:如何将日期字符串(YYYY-MM-DD)增加1天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆