繁体   English   中英

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

[英]JavaScript calculating date from today date to 7 days before

我从今天开始计算日期前 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);
}

问题解决了

var days; // Days you want to subtract
var date = new Date();
var last = new Date(date.getTime() - (days * 24 * 60 * 60 * 1000));
var day =last.getDate();
var month=last.getMonth()+1;
var year=last.getFullYear();

纯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 天,以毫秒为单位)。

如果您没有计划更改减去的值,您可以使用计算值,或者计算用于轻松更改减去的天数、分钟数等。


日期操作库

如果您计划更频繁地使用日期和时间,如果您关心时区、更小的 date- fns或更小但功能更少的 dayjs,我建议使用Luxon 相比

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/

您可以使用以下代码获取从今天日期到 7 天前的日期

var date = new Date();
date.setDate(date.getDate() - 7);

var finalDate = date.getDate()+'/'+ (date.getMonth()+1) +'/'+date.getFullYear();

试图减去天数是很棘手的。 最好从时间戳中减去并更改日期。

要减去 12 天,请执行以下操作:

   var d = new Date();
   var ts = d.getTime();
   var twelveDays = ts - (12 * 24 * 60 * 60 * 1000);
   d.setUTCDate(twelveDays);

更新 :)

var timeFrom = (X) => {
    var dates = [];
    for (let I = 0; I < Math.abs(X); I++) {
        dates.push(new Date(new Date().getTime() - ((X >= 0 ? I : (I - I - I)) * 24 * 60 * 60 * 1000)).toLocaleString());
    }
    return dates;
}
console.log(timeFrom(-7)); // Future 7 Days
console.log(timeFrom(7)); // Past 7 Days

输出

[
  '7/26/2019, 3:08:15 PM',
  '7/27/2019, 3:08:15 PM',
  '7/28/2019, 3:08:15 PM',
  '7/29/2019, 3:08:15 PM',
  '7/30/2019, 3:08:15 PM',
  '7/31/2019, 3:08:15 PM',
  '8/1/2019, 3:08:15 PM'
]
[
  '7/26/2019, 3:08:15 PM',
  '7/25/2019, 3:08:15 PM',
  '7/24/2019, 3:08:15 PM',
  '7/23/2019, 3:08:15 PM',
  '7/22/2019, 3:08:15 PM',
  '7/21/2019, 3:08:15 PM',
  '7/20/2019, 3:08:15 PM'
]

以 Array 的形式获取过去的日子,请使用此代码

结果见控制台

 const GetDays = (d,Mention_today=false)=>{ //Mention today mean the array will have today date var DateArray = []; var days=d; for(var i=0;i<days;i++){ if(!Mention_today && i==0){i=1;days+=1} var date = new Date(); var last = new Date(date.getTime() - (i * 24 * 60 * 60 * 1000)); var day =last.getDate(); var month=last.getMonth()+1; var year=last.getFullYear(); const fulld = (Number(year)+'-'+Number(month)+'-'+Number(day)) // Format date as you like DateArray.push(fulld); } return DateArray; } console.log(GetDays(5)) //Will get the past 5 days formated YY-mm-dd

 Date.prototype.addDays = function(days) { // Add days to given date var date = new Date(this.valueOf()); date.setDate(date.getDate() + days); return date; } let today = new Date() console.log(today.addDays(-7))

第一:获取当前日期

 const startingDate = new Date();

第二:得到你想要的日期!!:如果你直接使用setDate改变startingDate,它会改变这个变量。

const sevenDaysBeforeDate = new Date(new Date().setDate(new Date().getDate() - 7));

7天后

const endDate = new Date(new Date().setDate(new Date().getDate() + 7));

这是一个函数,它根据以下返回过去或将来的日期;

If plusMinus = -1 then Past Date
If plusMinus = 1 then Future Date

function getDate(inDays, plusMinus) {
    const today = new Date(); 
    return new Date(today.getFullYear(),
                    today.getMonth(),
                    today.getDate() + (inDays * plusMinus));
}

使用 dayjs 库,我们可以更轻松地完成它。

import dayjs from 'dayjs';

const getDate = (prevDays) => {
    const now = dayjs();
    console.log(now.subtract(prevDays, 'day').format('mm-dd-yyyy'));
    return now.subtract(prevDays, 'day').toDate();
}

这是最好的解决方案..当 X 是你的一天:

var dates = [];
for (let i = 0; i < X; i++) {
  var date = new Date();

  var thatDay = date.getDate() - i; //Current Date
  date.setDate(thatDay);
  let day = date.getDate();
  let month = date.getMonth() + 1;
  let year = date
    .getFullYear()
    .toString()
    .substr(-2);

  dates.push(month + '/' + day + '/' + year); //format it as you need
}
//output mm/d/yy

谢谢您的帮助。 我只是使用了一个简单的功能,效果很好

const subtractDayFromDate = (date, days) => {
  const newDate = new Date(date);
  newDate.setDate(newDate.getDate() - days);
  return newDate;
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM