合并日期格式化变量和函数 (jquery/Javascript)

Combine date formatting vars and functions (jquery/Javascript)

我有一些 javascript 可以获取不同的日期范围并将它们格式化为 return yyyymmdd。我得到了我需要的最终结果,但是有 2 个不同的变量让我感到困扰,让我觉得我没有以最好的方式做到这一点。我想知道是否有一种方法可以在一行中传递新日期和额外删除 - 所有这些。

我的函数是:

function toJSONLocalMonth (firstDay, lastDay) {//set default date range to from beggining of this month
    var local = new Date(firstDay);
    local.setMinutes(firstDay.getMinutes() - firstDay.getTimezoneOffset());
    return local.toJSON().slice(0, 10); 

    var local = new Date(lastDay);
    local.setMinutes(lastDay.getMinutes() - lastDay.getTimezoneOffset());
    return local.toJSON().slice(0, 10);
}

每当我需要结果时,我都会这样做:)今天和昨天的例子)

var dateToday = new Date();
dateTodayFormat = toJSONLocalMonth(dateToday).replace(/-/g, "");//format date yyyymmdd
dateYesterday = dateToday.setDate(dateToday.getDate() - 1);
dateYesterdayFormat = toJSONLocalMonth(dateToday).replace(/-/g, "");

如果有更好的方法来获得这个结果,或者至少将 dateYesterdaydateYesterdayFormat 组合到一行以获得 yyymmdd。

(我需要在函数结果中保留-,所以我不能在那里过滤它。)

谢谢!

你的问题不清楚。

toJSONLocalMonth 只会 return 一个值,第一个 return 语句中的值。第二个从未达到。

dateToday.setDate(...) 中的 return 值是时间值(数字),而不是日期,因此您不能将字符串方法链接到它。它会修改日期本身,因此 dateYesterday 是多余的,即

dateYesterday = dateToday.setDate(dateToday.getDate() - 1);
dateYesterdayFormat = toJSONLocalMonth(dateToday).replace(/-/g, ""); 

可以是:

dateToday.setDate(dateToday.getDate() - 1);
var dateYesterdayFormat = toJSONLocalMonth(dateToday).replace(/-/g, ""); 

toJSONLocalMonth 似乎只是获取格式为 YYYYMMDD 的日期字符串。我猜您正在避免使用内置 ISO 方法,因为它们使用 UTC/GMT 而不是本地时区。下面的函数以更明显的方式做到了这一点:

/*  Return an ISO 8601 formatted date string
**  @param {Date} d - date to create string for
**  @returns {string} string formatted as ISO 8601 without timezone
*/
function toISOStringLocal(d) {
  function z(n){return (n<10?'0':'') + n}
  return d.getFullYear() + '-' + z(d.getMonth()+1) + '-' +
         z(d.getDate()) + 'T' + z(d.getHours()) + ':' +
         z(d.getMinutes()) + ':' + z(d.getSeconds())
          
}

console.log(toISOStringLocal(new Date));

您也可以考虑像 fecha.js 这样的小型格式库,您可以在其中执行以下操作:

var dateToday = new Date();
var dateTodayFormat = fecha.format(dateToday, 'YYYYMMDD')
dateToday.setDate(dateToday.getDate() - 1);
var dateYesterdayFormat = fecha.format(dateToday, 'YYYYMMDD');

最后两行可以合并为一行:

var dateYesterdayFormat = fecha.format(new Date(dateToday.setDate(dateToday.getDate() - 1)), 'YYYYMMDD');

但我不推荐这样做。

另见:Where can I find documentation on formatting a date in JavaScript?