Hi I need help with tweaking my datesAgo function. What it does is it gives me a collection of dates from the date that is passed through counting backwards but my problem with my function is that it's not showing the 3rd date correctly it should be 17 instead of 16 can someone see if they know why it's happing like that
Date.prototype.datesAgo = function(num) {
let date = this;
let arr = [];
for(let i = 0; i < num; i++) {
arr.push(i.toString());
}
let days = arr.slice(0, num).join(' ');
console.log(days)
return days.split(' ').map(function(n) {
date.setDate(date.getDate() - n);
return (function(year, month, day) {
return [year, month < 10 ? '0'+ month : month, day < 10 ? '0' + day : day].join('-');
})(date.getFullYear(), date.getMonth(), date.getDate());
}).join(',');
}
console.log(new Date('2018-05-19').datesAgo(3))
On each iteration, you're mutating the original date object:
date.setDate(date.getDate() - n);
So, on each subsequent iteration, you're subtracting n from the last iteration's date, not the original date. Clone the original date object on each iteration instead:
Date.prototype.datesAgo = function(num) {
const date = this;
const dateStrs = Array.from({ length: num }, (_, i) => {
const clonedDate = new Date(date.getTime());
clonedDate.setDate(date.getDate() - i);
return (function(year, month, day) {
return [year, month < 10 ? '0' + month : month, day < 10 ? '0' + day : day].join('-');
})(clonedDate.getFullYear(), clonedDate.getMonth(), clonedDate.getDate());
});
return dateStrs.join(',');
}
console.log(new Date('2018-05-19').datesAgo(3))
Related
How to can I make this sequence of date with tri-monthly. for eg. the input is `"2022-03-14" the input is dynamic it depends on the user input... I'm trying add + 10 days but isn't working
The output I want
[
"2022-03-24",
"2022-04-04",
"2022-04-14",
"2022-04-24",
"2022-05-04",
"2022-05-14",
"2022-05-24",
"2022-06-04",
"2022-06-14",
"2022-06-24",
]
My code output which is worng
[
"2022-03-24",
"2022-04-14",
"2022-04-24",
"2022-05-14",
"2022-05-24",
"2022-06-14",
"2022-06-24",
"2022-07-14",
"2022-07-24",
]
function createSchedule(date, count){
date = new Date(date);
let day = date.getDate();// Get day in given date
let k = 0;
let days = k? [day - 10, day , day + 10] : [day, day + 10, day- 10];
let result = [];
if(day > 10){
k = +0
}else{
if(day > 20 ){
k = +1
}else{
k= +2
}
}
for(let i = 0; i < count; i++){
k= 1-k;
date.setDate(days[k]);
// When date overflows into next month, take last day of month
if (date.getDate() !== days[k]) date.setDate(0);
if (!k) date.setMonth(date.getMonth() + 1);
result.push(date.toLocaleDateString("en-SE"));
}
return result
}
var dateRelease = new Date("03-14-2022");
var result = createSchedule(dateRelease, 9);
console.log(result)
A few issues in your attempt:
After let k = 0, the conditional operator on k? will always evaluate the first expression after ?, which is [day - 10, day , day + 10].
That array could have dates that are greater than 31 (day + 10)
That other array [day, day + 10, day- 10] is not sorted, but should be.
The constants +0 and +1 and +2 are OK, but it looks odd that you use the unary plus here. It could just be 0, 1 and 2.
The assignment k = 1 - k assumes you only have two entries in your days array, but you have three, so use modular arithmetic: k = (k + 1) % 3
Here is a correction:
function createSchedule(date, count) {
date = new Date(date);
let day = date.getDate();
let firstDay = 1 + (day - 1) % 10;
let days = [firstDay, firstDay + 10, firstDay + 20];
let k = days.indexOf(day);
let result = [];
for (let i = 0; i < count; i++) {
k = (k + 1) % 3;
date.setDate(days[k]);
// When date overflows into next month, take last day of month
if (date.getDate() !== days[k]) date.setDate(0);
if (!k) date.setMonth(date.getMonth() + 1);
result.push(date.toLocaleDateString("en-SE"));
}
return result;
}
var dateRelease = new Date("2022-03-14");
var result = createSchedule(dateRelease, 25);
console.log(result);
Is there anyway to get the days past the current day using MomentJS?
For example suppose it is January 5, 2018, how would I get the previous dates from January 1, 2018 through to January 5, 2018 ?
My current code looks like this:
const monthArr = [];
const dayArr= [];
const currentDate = moment(new Date()).format("DD");
for (let i = 0; i < +currentDate; i++) {
const month = moment(new Date())
.subtract(i, "day")
.format("MMYYYY");
const day = moment(new Date())
.subtract(i, "day")
.format("MMDDYYYY");
console.log("month" + month);
console.log("day" + day);
let monthObj = {};
let dailyObj = {};
monthArr.push(
(monthObj = {
data: {
[month]: Object.assign({}, document)
}
})
);
day.push(
(dailyObj = {
data: {
[day]: Object.assign({}, document)
}
})
);
monthly(user_id, monthArr[i]) &&
daily(user_id, dayArr[i]);
}
The code in the OP seems very inefficient and far more complex than required.
To generate a series of formatted strings for dates from today to the start of the month only needs one Date and some very simple arithmetic and formatting. It really doesn't need a library nor any date arithmetic, e.g.
// Pad single digit number with leading zero
function pad(n){
return (n < 10? '0' : '') + n;
}
var today = new Date(),
year = today.getFullYear(),
month = pad(today.getMonth() + 1),
day,
i = today.getDate();
do {
day = pad(i);
console.log(`Month: ${month + year}`);
console.log(`Day: ${month + day + year}`);
} while (--i)
There are a number of other issues with your code, but they're not directly related to the question.
From JavaScript is there a way to get list of days between two dates from MySQL format. I don't want to use any library for this.
This is what i did.
function generateDateList(from, to) {
var getDate = function(date) { //Mysql Format
var m = date.getMonth(), d = date.getDate();
return date.getFullYear() + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d);
}
var fs = from.split('-'), startDate = new Date(fs[0], fs[1], fs[2]), result = [getDate(startDate)], start = startDate.getTime(), ts, end;
if ( typeof to == 'undefined') {
end = new Date().getTime();
} else {
ts = to.split('-');
end = new Date(ts[0], ts[1], ts[2]).getTime();
}
while (start < end) {
start += 86400000;
startDate.setTime(start);
result.push(getDate(startDate));
}
return result;
}
console.log(generateDateList('2014-2-27', '2014-3-2'));
I test it from chrome and nodejs below are the result.
[ '2014-02-27',
'2014-02-28',
'2014-02-29',
'2014-02-30',
'2014-02-31',
'2014-03-01',
'2014-03-02' ]
yeh big leap year:-D..., how can i fix this? or is there any better way.?
const listDate = [];
const startDate ='2017-02-01';
const endDate = '2017-02-10';
const dateMove = new Date(startDate);
let strDate = startDate;
while (strDate < endDate) {
strDate = dateMove.toISOString().slice(0, 10);
listDate.push(strDate);
dateMove.setDate(dateMove.getDate() + 1);
};
Take the start date and increment it by one day until you reach the end date.
Note: MySQL dates are standard format, no need to parse it by hand just pass it to the Date constructor: new Date('2008-06-13').
const addDays = (date, days = 1) => {
const result = new Date(date);
result.setDate(result.getDate() + days);
return result;
};
const dateRange = (start, end, range = []) => {
if (start > end) return range;
const next = addDays(start, 1);
return dateRange(next, end, [...range, start]);
};
const range = dateRange(new Date("2014-02-27"), new Date("2014-03-02"));
console.log(range);
console.log(range.map(date => date.toISOString().slice(0, 10)))
Here I use a recursive function, but you could achieve the same thing using a while (see other answers).
I have used this one from
https://flaviocopes.com/how-to-get-days-between-dates-javascript/
const getDatesBetweenDates = (startDate, endDate) => {
let dates = []
//to avoid modifying the original date
const theDate = new Date(startDate)
while (theDate < new Date(endDate)) {
dates = [...dates, new Date(theDate)]
theDate.setDate(theDate.getDate() + 1)
}
dates = [...dates, new Date(endDate)]
return dates
}
Invoke the function as follows:
getDatesBetweenDates("2021-12-28", "2021-03-01")
Note - I just had to fix issues with the Date object creation (new Date()) in the while loop and in the dates array. Other than that the code is pretty much same as seen on the above link
dateRange(startDate, endDate) {
var start = startDate.split('-');
var end = endDate.split('-');
var startYear = parseInt(start[0]);
var endYear = parseInt(end[0]);
var dates = [];
for(var i = startYear; i <= endYear; i++) {
var endMonth = i != endYear ? 11 : parseInt(end[1]) - 1;
var startMon = i === startYear ? parseInt(start[1])-1 : 0;
for(var j = startMon; j <= endMonth; j = j > 12 ? j % 12 || 11 : j+1) {
var month = j+1;
var displayMonth = month < 10 ? '0'+month : month;
dates.push([i, displayMonth, '01'].join('-'));
}
}
return dates;
}
var oDate1 = oEvent.getParameter("from"),
oDate2 = oEvent.getParameter("to");
var aDates = [];
var currentDate = oDate1;
while (currentDate <= oDate2) {
aDates.push(new Date(currentDate));
currentDate.setDate(currentDate.getDate() + 1);
}
I expanded Công Thắng's great answer to return {years, months, days}, thought it was worth sharing:
function getDates(startDate, endDate) {
const days = [],
months = new Set(),
years = new Set()
const dateMove = new Date(startDate)
let date = startDate
while (date < endDate){
date = dateMove.toISOString().slice(0,10)
months.add(date.slice(0, 7))
years.add(date.slice(0, 4))
days.push(date)
dateMove.setDate(dateMove.getDate()+1) // increment day
}
return {years: [...years], months: [...months], days} // return arrays
}
console.log(getDates('2016-02-28', '2016-03-01')) // leap year
/* =>
{
years: [ '2016' ],
months: [ '2016-02', '2016-03' ],
days: [ '2016-02-28', '2016-02-29', '2016-03-01' ]
}
*/
const {months} = getDates('2016-02-28', '2016-03-01') // get only months
Basically the function just increments the built-in Date object by one day from start to end, while the Sets capture unique months and years.
Is there any javascript function which takes one input parameter (e.g 04/2014 ) and return
12 months and dates with the same format
(e.g 04/2013.........................................04/2014)
i have this one
function calcFullMonth(startDate) {
//copy the date
var dt = new Date(startDate);
dt.setMonth(dt.getMonth() - 1);
return dt;
}
The logic that i have is this .But it gives me only one month back
I need to get 12 months and 1 year back and display them as you see second e.g.
Thanks
Just call your original function as many times as you need, and store them in an array.
function calcFullMonth(startDate, num) {
var months = [];
for (var i = 0; i < num; i++) {
var dt = new Date(startDate);
dt.setMonth(dt.getMonth() + i);
months[i] = dt;
}
return months;
}
For example, to get the current month until this month next year, use num = 13
console.log(calcFullMonth(new Date(), 13));
fiddle
Try the following function
function Get12MonthBack(input) {
var year = input.split("/")[1];
var month = input.split("/")[0];
var d = new Date(year, month);
d.setMonth(d.getMonth()-12);
return (d.getMonth().toString().length == 1 ? "0" + d.getMonth() : d.getMonth()) + "/" + d.getFullYear();
}
Tests
Get12MonthBack("03/2011")
"03/2010"
Get12MonthBack("11/2012")
"11/2012"
i am writing a function in javascript that will return date array of all sundays.
below you can see my code :
function getDefaultOffDays(year){
var offdays=new Array();
i=0;
for(month=1;month<12;month++)
{
tdays=new Date(year, month, 0).getDate();
for(date=1;date<=tdays;date++)
{
smonth=(month<10)?"0"+month:month;
sdate=(date<10)?"0"+date:date;
dd=year+"-"+smonth+"-"+sdate;
day=new Date();
day.setDate(date);
day.setMonth(month);
day.setFullYear(year);
if(day.getDay() == 0 )
{
offdays[i++]=dd;
}
}
}
return offdays;
}
the issue is that the returned array is giving random dates not the only dates for sunday :(
m i missing some thing?
If you examine the result, you can see that it's actually not random. It returns the dates for january that are sundays in february, and so on.
The month property of the Date object is zero based, not one based. If you change this line, the function will return the correct dates:
day.setMonth(month - 1);
Also, the loop only runs from 1 to 11, you need to include december too:
for (month=1; month <= 12; month++)
Another way to do this would be to find the first sunday, then just step forward seven days at a time:
function getDefaultOffDays2(year) {
var date = new Date(year, 0, 1);
while (date.getDay() != 0) {
date.setDate(date.getDate() + 1);
}
var days = [];
while (date.getFullYear() == year) {
var m = date.getMonth() + 1;
var d = date.getDate();
days.push(
year + '-' +
(m < 10 ? '0' + m : m) + '-' +
(d < 10 ? '0' + d : d)
);
date.setDate(date.getDate() + 7);
}
return days;
}
One bug:
for(month=1;month<12;month++)
That's just 11 months.
If you want for the whole year you need:
for(month=0;month<12;month++)
Because there are 12 months in a year. You can even combine that with Guffa's answer.
Month is zero based as like day, so if month is 0 then it Jan, So changed your code as below,
function getDefaultOffDays(year){
var offdays=new Array();
i=0;
for(month=0;month<12;month++) {
tdays=new Date(year, month, 0).getDate();
for(date=1;date<=tdays;date++) {
smonth=(month<10)?"0"+(month+1):(month+1);
sdate=(date<10)?"0"+date:date;
dd=year+"-"+smonth+"-"+sdate;
var day=new Date(year,month,date);
if(day.getDay() == 0 ) {
offdays[i++]=dd;
}
}
}
return offdays;
}
This function has error
error code:
tdays=new Date(year, month, 0).getDate();
replace to:
tdays=new Date(year, month, 1).getDate();
becouse 0(day) return prev month