【问题标题】:Why can't I display JUST the date (date, month, and year without time)?为什么我不能只显示日期(没有时间的日期、月份和年份)?
【发布时间】:2018-09-24 11:13:34
【问题描述】:

我有一些代码,它几乎完成了我需要它做的所有事情。它计算未来 3 天,不包括日期,然后显示我的“预计发货日期”

但是,日期以完整的日期和时间显示,而不仅仅是日期。
日月日年 12:02:57 GMT+0100(英国夏令时)

任何人都可以帮助使用下面的代码,以便它不包括当地时间,只显示未来日期,不包括周末,
DD/MM/YYYY
或者,在下面格式;
6 月 20 日星期一

提前致谢!

function addDates(startDate,noOfDaysToAdd){
var count = 0;
while(count < noOfDaysToAdd){
endDate = new Date(startDate.setDate(startDate.getDate() + 1));
if(endDate.getDay() != 0 && endDate.getDay() != 6){
   //Date.getDay() gives weekday starting from 0(Sunday) to 6(Saturday)
   count++;
}
}
return startDate;
}
var today = new Date();
var daysToAdd = 3;
document.write ('Estimated Dispatch Date: ' + addDates(today,daysToAdd));

【问题讨论】:

  • 那是 JavaScript 吗?我建议您为编程语言添加一个标签,以更好地吸引那些知道您的问题的人。我还推荐更好的代码缩进。

标签: javascript date datetime


【解决方案1】:

您可以使用toDateString 方法仅显示Date 对象的日期部分,但您需要使用其他一些方法来完全控制日期字符串的格式...

您可以使用getDate、getMonth 和getFullYear 方法帮助格式化,只显示本地日期和时间的日期、月份和年份部分,并添加几行代码。您可以尝试将特定格式参数传递给toLocaleString,但这可能会在不同的浏览器中显示不同的结果。例如,下面的代码在 Chrome 中以 dd/mm/yyyy 格式输出日期,但不能保证跨浏览器的输出。

new Date().toLocaleString('en-GB', {year: 'numeric', month: 'numeric', day: 'numeric'})

不确定我是否在关注您希望如何处理周末日期,因此下面将处理您在 formatDate 函数中所需的日期格式,与 addDays 函数分开处理,后者只是通过向前滚动日期来处理周末日期如果最初计算的日期是星期六或星期日,则改为星期一。

// format input date to dd/mm/yyyy
const formatDate = (date) => {
  const d = date.getDate(); // day of the month
  const m = date.getMonth(); // month index from 0 (Jan) to 11 (Dec)
  const yyyy = date.getFullYear(); // 4 digit year
  const dd = (d < 10 ? '0' : '') + d; // format date to 2 digit
  const mm = (m + 1 < 10 ? '0' : '') + (m + 1); // convert index to month and format 2 digit
  return `${dd}/${mm}/${yyyy}`;
};

// add input days to today and adjust for weekend output
const addDays = (today, days) => {
  const now = today.getTime() // now in UTC milliseconds
  const ms = 24 * 60 * 60000; // milliseconds in one day
  const date = new Date((days * ms) + now); // today plus input days
  const day = date.getDay(); // weekday index from 0 (Sun) to 6 (Sat)
  // adjust weekend results to next weekday
  if (day === 0 || day === 6) {
    let adj = day === 0 ? 1 : 2;
    return new Date(((days + adj) * ms) + now);
  }
  
  return date;
};

document.write('Estimated Dispatch Date: ' + formatDate(addDays(new Date(), 3)));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-07
    • 2018-10-15
    • 1970-01-01
    • 1970-01-01
    • 2011-06-27
    • 2021-12-15
    相关资源
    最近更新 更多