gpt4 book ai didi

JavaScript 将日期设置为 x 的开头

转载 作者:行者123 更新时间:2023-12-03 12:29:12 25 4
gpt4 key购买 nike

我正在开发一个 fn,它将日期设置为分钟/小时/天/周/月/季度/年的开始。

我从本周开始做如下事情:

var date = new Date(),
day = d.getDay(),
// adjust when day is sunday
diff = d.getDate() - day + (day == 0 ? -6 : 1);

var updatedDate = new Date(date.setDate(diff);

但我想知道是否有更好的方法(或框架)来完成此类事情?

最佳答案

这是迄今为止我能想到的最好的:

function beginningOf(period, date) {
date = new Date(date.valueOf()); // copy date

if (period === "year" || period == "quarter") {
date.setMonth(period === "quarter"
? 3 * Math.floor(date.getMonth() / 3)
: 0);
period = "month"; // now round down to the start of this month
}

if (period === "month" || period === "week") {
date.setDate(period === "week"
? date.getDate() - date.getDay() // Sunday is the first day, adjust to suit
: 1);
period = "day"; // now round dow to the start of this day
}

// intentional switch fall-through
switch (period) {
case "day":
date.setHours(0);
case "hour":
date.setMinutes(0);
case "minute":
date.setSeconds(0);
date.setMilliseconds(0);
}

return date;
}

参见http://jsfiddle.net/alnitak/6hj9u/

这是一个比我预想的稍微难一点的问题......

关于JavaScript 将日期设置为 x 的开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24018530/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com