gpt4 book ai didi

JavaScript计算从今天到7天前的日期

转载 作者:数据小太阳 更新时间:2023-10-29 04:21:52 24 4
gpt4 key购买 nike

我正在计算从今天开始的日期前 12 天。但它不会返回正确的日期。例如,对于今天 dat,11/11/2013 in (mm/dd/yyyy),它返回 10/30/2013 而它应该返回 10/31/2013。

这是代码

var d = new Date();
d.setDate(d.getDate() - 12);
d.setMonth(d.getMonth() + 1 - 0);
var curr_date = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
if (curr_month < 10 && curr_date < 10) {
var parsedDate = "0" + curr_month + "/" + "0" + curr_date + "/" + curr_year;
alert(parsedDate);
} else if (curr_month < 10 && curr_date > 9) {
var parsedDate = "0" + curr_month + "/" + curr_date + "/" + curr_year;
alert(parsedDate);
} else if (curr_month > 9 && curr_date < 10) {
var parsedDate = curr_month + "/" + "0" + curr_date + "/" + curr_year;
alert(parsedDate);
} else {
var parsedDate = curr_month + "/" + curr_date + "/" + curr_year;
alert(parsedDate);
}

最佳答案

纯js一行解决方案:

const sevenDaysAgo: Date = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)  
  1. new Date() - 从计算的毫秒时间创建 Date 对象。
  2. Date.now() - 给出从 1970 年到现在的时间(以毫秒为单位)。
  3. 7(天)* 24(小时)* 60(分钟)* 60(秒)* 1000(毫秒)= 604800000(7 天,以毫秒为单位)。

如果您不打算更改减去的值,或者为了轻松更改减去的天数、分钟数等,可以使用计算值。


日期操作库

如果您打算更频繁地处理日期和时间,我建议使用 Luxon如果你关心timezones , date-fns哪个更小或 dayjs它更小但功能更少。 Compare

import { format, formatDistance, formatRelative, subDays } from 'date-fns'

format(new Date(), "'Today is a' eeee")
//=> "Today is a Friday"

formatDistance(subDays(new Date(), 3), new Date(), { addSuffix: true })
//=> "3 days ago"

formatRelative(subDays(new Date(), 3), new Date())
//=> "last Friday at 7:26 p.m."

为什么不用 moment.js?

Moment.js 被认为是处于维护模式的遗留项目。它没有死,但确实已经完成了。参见 https://momentjs.com/docs/#/-project-status/

关于JavaScript计算从今天到7天前的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19910161/

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