Get date of exactly 6 days ago from today in JS [duplicate] - javascript

This question already has answers here:
How to subtract days from a plain Date?
(36 answers)
Closed 3 years ago.
Thank you in advance
I would like your help with getting 'days ago' from a particular date. I don't want to use any library.
Although I have tried moment JS.

Use getDate() and subtract the number of days from it
var d = new Date();
d.setDate(d.getDate() - 6);
console.log(d);

First, make a new Date with your date:
const date = new Date('December 17, 1995 03:24:00');
Second, subtract 6 days like so:
date.setDate(date.getDate() - 6);
Third, use date.toString() :
console.log(date.toString());

You question title and description contradict with each other.
The following function that return number of days ago can help if this is what you need:
function getDaysAgo(date, now = new Date()) {
//first calculating start of the day
const start = now.setHours(0, 0, 0, 0);
//then calculating difference in miliseconds
const diff = start - date.getTime();
//finally rounding to a bigger whole days
const result = Math.ceil(diff/(1000*60*60*24));
//as a bonus returning today/yesterday/future when necessary
if (result < 0) {
return 'in future';
}
if (result === 0) {
return 'today';
}
return result === 1 ? 'yesterday' : result + ' days ago';
}
For example getDaysAgo(new Date(Date.parse('2019-9-28 23:59')), new Date(Date.parse('2019-9-30 10:59'))) returns 2 days ago.

It is a simple function that returns a new desire past date.
function getNthDate(nthDate){
let date = new Date();
return new Date(date.setDate(date.getDate() - nthDate))
}
Live example

Related

Convert number of days left into years, months, days [duplicate]

This question already has answers here:
Difference between two dates in years, months, days in JavaScript
(34 answers)
How to get difference between 2 Dates in Years, Months and days using moment.js
(3 answers)
How to get the difference of two dates in mm-dd-hh format in Javascript
(3 answers)
Closed 2 years ago.
I am trying to get the difference between two dates (my birthday and the current date to get the time left until my birthday), But I want the output format in ('Year/Months/Days); How can I do that? that's what I've tried so far :
const birthday = new Date ('11-20-2021').getTime();
const today = new Date ().getTime();
const dys = (1000*60*60*24);
const months = (dys*30);
let differance = birthday-today ;
const formatted = Math.round(differance/dys);
console.log(formatted);`
thank you in advance
How do you feel about the modulo operator? :)
This is a common math operation, like finding change or such. Think of it this way, if you have a large number of days, say 397, you can get number of years by doing integer division (1), then you can get the number of days left by doing modulo by a year to get the remainder (in days) 397%365 = 32. Then you can repeat the process to get number of months remaining (1...assuming 30 day month) in that and again, modulo to get the final number of days 2 ...
I'm no javascript pro, but I think you need to use Math.floor(quotient) to get the result of division in integer format.
this example compares between the current date and the date 2100/0/14 try the same concept in the example and i hope it helps:
var today, someday, text;
today = new Date();
someday = new Date();
someday.setFullYear(2100, 0, 14);
if (someday > today) {
text = "Today is before January 14, 2100.";
} else {
text = "Today is after January 14, 2100.";
}
document.getElementById("demo").innerHTML = text;
Working with dates and differences can be difficult because there are a lot of edge cases. which is why I prefer to let a dedicated library handle this, like https://momentjs.com/
moment has a plugin (https://www.npmjs.com/package/moment-precise-range-plugin) which does exactly what you are looking for:
import moment from 'moment';
import 'moment-precise-range-plugin';
var m1 = moment('2014-01-01 12:00:00','YYYY-MM-DD HH:mm:ss');
var m2 = moment('2014-02-03 15:04:05','YYYY-MM-DD HH:mm:ss');
var diff = moment.preciseDiff(m1, m2, true); // {years : 0, months : 1, days : 2, hours : 3, minutes : 4, seconds : 5}
var str = `Years: ${diff.years}, Months: ${diff.months}, Days: ${diff.days} `; // 'Years: 0, Months: 1, Days: 2'
If I got you right, I've done it this way.
Haven't touched your original code, but added a function that calculates the dateTime output of the total days of difference.
const birthday = new Date('11-20-2021').getTime();
const today = new Date().getTime();
const dys = (1000 * 60 * 60 * 24);
const months = (dys * 30);
let totalDayserance = birthday - today;
const formatted = daysToDateTime(totalDayserance / dys);
console.log(formatted);
function daysToDateTime(totalDays) {
var baseVal = '';
var formedValues = [
['Years', 365],
['Months', 30],
['Days', 1]
];
for (var i = 0; i < formedValues.length; i++) {
var valueByGroup = Math.floor(totalDays / formedValues[i][1]); //by months
if (valueByGroup >= 1) {
baseVal += (valueByGroup + formedValues[i][0]) + ', ';
totalDays -= valueByGroup * formedValues[i][1];
}
}
return baseVal;
}

How to get the date in days ago in javascript [duplicate]

This question already has answers here:
How to calculate number of days between two dates?
(42 answers)
Closed 3 years ago.
So,
I have this
10 Dec, 2019T14:07:21
format of date coming from backend , what I need is to find how many days ago.
like today is 20 , so for todays date it will give 0 days ago.
You can try this code.
var date1 = new Date("12/13/2010");
var date2 = new Date("12/20/2010");
var diffDays = parseInt((date2 - date1) / (1000 * 60 * 60 * 24), 10);
console.log(diffDays )
You can compare two dates. Substracting them will give you the miliseconds difference. THose miliseconds can be converted into days.
const now = new Date();
// Mimick a backend date
const daysAgo = new Date();
daysAgo.setDate(daysAgo.getDate() - 10);
// Compare both, outputs in miliseconds
const diffMs = now - daysAgo;
// Get the number of days by dividing by the miliseconds in a single day
const daysDiff = Math.round(diffMs/(1000*60*60*24));
console.log(daysDiff)
(new Date()-new Date("10 Dec, 2019T14:07:21".replace("T"," ")))/1000/60/60/24
What you try to do is called "date diff" meaning you want to find the difference in days between 2 dates. First of all you need to create a new Date object from the string you want. You can do that using Moment.js library that will parse your date string and return a Date object.
var date1 = moment("10 Dec, 2019T14:07:21", "DD MMM, YYYY");
var date2 = new Date() //today date
A simple js function accomplishing that is the one below
function dateDiff(date1, date2) {
var datediff = date1.getTime() - date2.getTime();
return (datediff / (24*60*60*1000));
}
dateDiff function will return the difference between dates, so if date1 is a previous day, it will return a negative number of days. In order to convert it to the "x days ago" format you need, you need to simply multiply the result by -1.

How to get a special list of dates in every month in a given range using moment.js [duplicate]

This question already has answers here:
add month to a date moment js
(3 answers)
Closed 4 years ago.
Let's assume start date is 2019-01-10. We have to check 15 months ahead.
So the end date is 2020-04-10.
I want to get a list of every 10th of the day in each month in the above list.
Like following :
['2019-01-10' , '2019-02-10' , '2019-03-10' , '2019-04-10' , ...... ,
'2020-04-10' ]
How can I do this in moment,js ?
If this is not possible in moment.js, what are the ways we can do this in JavaScript ?
In vanilla JavaScript just use Date.setMonth. For starting dates such as 29, 30 and 31 the resulting dates will roll over into next month so you must handle that case.
function buildDates(startDate, months) {
return Array.from({
length: months
}, function(_, i) {
var date = new Date(startDate.getTime());
var mnth = date.getMonth();
date.setMonth(mnth + i);
if (date.getMonth() !== (mnth + i) % 12) {
date.setDate(0);
}
return date;
});
}
console.log(buildDates(new Date(2019, 0, 10), 15));
console.log(buildDates(new Date(2019, 0, 31), 15));
You can move date by n months via add method. Something like this:
function dateOffsetByMonths(months, dateStr, format) {
var startDate = moment(dateStr, format);
return Array.from(Array(months + 1).keys()).reduce(function(res, n, i) {
var date = startDate.clone();
date.add(i, 'months');
res.push(date.format('YYYY-MM-DD'));
return res;
}, []);
}
console.log(dateOffsetByMonths(15, '2019-01-10', 'YYYY-MM-DD'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
You can use array#from to accumulate all dates in an array. Keep adding the index to the initial date in each iteration.
function allDates(length, date, format) {
return Array.from({length}, (_, i) => moment(date, format).add(i, 'months').format(format));
}
console.log(allDates(15, '2019-01-31', 'YYYY-MM-DD'));
console.log(allDates(15, '2019-01-10', 'YYYY-MM-DD'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>

getYear() in JavaScript returns 118 [duplicate]

This question already has answers here:
Why does Javascript getYear() return a three digit number?
(14 answers)
getMonth in javascript gives previous month
(6 answers)
Closed 4 years ago.
I need to calculate the date of the last Monday that before the latest weekend. Having used what I believe to be the most common Stack Overflow suggestions I have the following code:
const getDayOfTheWeek = () => {
let date = new Date();
let clonedDate = new Date(date.getTime());
console.log(clonedDate);
const dow = clonedDate.getDay();
console.log(dow);
const offset = dow+6;
console.log(offset);
const newDate = new Date(clonedDate.setDate(clonedDate.getDate() - offset));
console.log(newDate);
const newNewDate = new Date(newDate.getTime());
console.log(newNewDate);
const day = newNewDate.getDate();
const month = newNewDate.getMonth();
const year = newNewDate.getYear();
console.log('the year is ',year, 'the month is ', month);
}
getDayOfTheWeek();
It returns the year as 118 and the month as 5 which are ... not that Monday I need. newNewDate, on the other hand is the last Monday. I was wondering what causes it. I am aware that there are too many reassignments that are not needed. Please help.
Whatever you are doing is perfect only, the only mistake is you are using getMonth() and getYear() and misunderstanding them.
date.getMonth() gives you months ranging from 0-11. So 5 is actually June month.
date.getYear() this method returns the year minus 1900, so actual is 118+1900=2018, instead you can use date.getFullYear() which will return 2018
Also, you don't need so many steps.
the function can be simply stopped with newDate as given below
const getDayOfTheWeek = () => {
let date = new Date();
let clonedDate = new Date(date.getTime());
console.log(clonedDate);
const dow = clonedDate.getDay();
console.log(dow);
const offset = dow+6;
console.log(offset);
const newDate = new Date(clonedDate.setDate(clonedDate.getDate() - offset));
console.log(newDate);
const day = newDate.getDate();
const month = newDate.getMonth() + 1;
const year = newDate.getFullYear();
console.log('the year is ',year, 'the month is ', month);
}
getDayOfTheWeek();
This will give "the year is 2018 the month is 6"
Hope this helps.

Get previous month date javascript [duplicate]

This question already has answers here:
How to get 30 days prior to current date?
(16 answers)
Closed 7 years ago.
How can I get previous month date in javascript. Suppose you have today's date like:
var abc = new date();
It will return today's date for example 03-11-2015. Now I want to get 03-10-2015. This is 30 days less than todays date. How can I do this?
var d = new Date();
d.setMonth(d.getMonth() - 1);
Check out momentjs, great little library for manipulating and formatting dates.
Complementing Robert Shenton's answer:
var d = new Date();
var newMonth = d.getMonth() - 1;
if(newMonth < 0){
newMonth += 12;
d.setYear(d.getFullYear() - 1); // use getFullYear instead of getYear !
}
d.setMonth(newMonth);

Categories