微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

根据jQuery中输入的日期字符串获取下一个日期(YYYY-MM-DD)

如何解决根据jQuery中输入的日期字符串获取下一个日期(YYYY-MM-DD)

考虑一下,我有一个格式为(年-月-日)的日期,

adate = "2020-10-02";

现在我想创建一个 jQuery 函数,输入 adate 并返回 next_date,如下所示,

function make_next_date(adate) {
  next_date = adate + 1; //"2020-10-03"
  return next_date;
}

功能应该在以下输入日期正常工作,

adate = "2021-05-31";
next_date = "2021-06-01";

adate = "2020-12-31";
next_date = "2021-01-01";

adate = "2021-02-28";
next_date = "2021-03-01";

解决方法

这只是 JavaScript。 JavaScript 有日期。 jQuery 与日期操作无关。


function make_next_date(adate) {
  next_date = new Date(adate);
  next_date.setDate(next_date.getDate() + 1);
  return next_date.toISOString().split('T')[0];
}

[
  "2021-05-31","2020-12-31","2021-02-28",].forEach(date => {
  console.log({
    date,out: make_next_date(date)
  });
});

,

function make_next_date(adate) {
  const date = new Date(adate);
  date.setDate(date.getDate() + 1);

  // YEAR
  const rYear = date.getFullYear();

  // MONTH
  let rMonth = date.getMonth() + 1;
  rMonth = rMonth < 10 ? `0${rMonth}` : rMonth;

  // DATE
  let rDate = date.getDate();
  rDate = rDate < 10 ? `0${rDate}` : rDate;

  return `${rYear}-${rMonth}-${rDate}`;
}

["2021-05-31","2021-02-28"].forEach((date) => {
  console.log({
    date,out: make_next_date(date),});
});

,

将您的字符串更改为日期对象。 并加1。 让日期 = 新日期(); date.SetDate(Date.parseDate(你的字符串 + 1);

,

可以使用Date类和padStart函数来实现。

let adate = "2020-10-02";

function make_next_date(adate) {
    const [year,month,day] = adate
        .split("-")
        .map(item => parseInt(item));

    const date = new Date(year,day);

    date.setDate(date.getDate() + 1);

    return [
        date.getFullYear(),date.getMonth().toString().padStart(2,0),date.getDate().toString().padStart(2,0)
    ].join("-")
}

console.log(make_next_date(adate));

另外,还有一个非常有用的日期操作包,叫做 moment。使用 moment 只需 3 行代码即可实现。

const moment = require("moment");
const FORMAT = "YYYY-MM-DD";

let adate = "2020-10-02";

function make_next_date(adate) {
    return moment(adate,FORMAT)
        .add(1,"day")
        .format(FORMAT);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。