How to manipulate date using Javascript - javascript

How can I achieve this sequence of date output if the user input is 04-29-2022 and the output is like this
What I want:
2022-05-14
2022-05-29
2022-06-14
2022-06-29
2022-07-14
2022-07-29
2022-08-14
2022-08-29
my code output
2022-05-13
2022-05-28
2022-06-12
2022-06-27
2022-07-12
2022-07-27
2022-08-11
2022-08-26
var dateRelease = new Date("04-29-2022")
const terms = 8
for (let i = 0; i < terms; i++) {
console.log(new Date(dateRelease.setDate(dateRelease.getDate() + 15)).toISOString().slice(0, 10))
}

Here is a function that takes the day of the month in the given date and determines which other date of the month would be needed in the output (either 15 more or 15 less). Then it generates dates alternating between those two date-of-the-month, and when it is the lesser of those two, incrementing the month. In case a date is invalid and automatically overflows into the next month, it is corrected to the last day of the intended month.
To format the date in the output, it is better to not use toISODateString as that interprets the date as a UTC Date, while new Date("2022-04-29") interprets the given string as a date in the local time zone. This can lead to surprises in some time zones. So I would suggest using toLocaleDateString with a locale that produces your desired format.
Here is the code:
function createSchedule(date, count) {
date = new Date(date);
let day = date.getDate();
let k = +(day > 15);
let days = k ? [day - 15, day] : [day, day + 15];
let result = [];
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("2022-04-29");
var result = createSchedule(dateRelease, 25);
console.log(result);

var dateRelease = new Date("04-29-2022")
const terms = 8
for (let i = 0; i < terms; i++) {
let date = new Date(dateRelease.setDate(dateRelease.getDate() + 15)).toLocaleDateString('en-US');
let format = date.split('/').map(d => d.padStart(2 ,'0')).join('-')
console.log(format);
}

Related

Given an ISO date, get the days of the week in form of ISO string ranges

Suppose I have an ISO date, such as 2021-09-18T20:18:27.000Z
I would like to get the dates of the past week in form of an array
The array should be a set of arrays that have two ISO dates that represent the start of the day and the end of the day as illustrated below:
E.g.
input:
2021-09-18T20:18:27.000Z
output:
[
['"2021-09-11T00:00:00.000Z', '"2021-09-11T23:59:59.000Z'],
['"2021-09-12T00:00:00.000Z', '"2021-09-11T23:59:59.000Z'],
['"2021-09-13T00:00:00.000Z', '"2021-09-11T23:59:59.000Z'],
['"2021-09-14T00:00:00.000Z', '"2021-09-11T23:59:59.000Z'],
['"2021-09-15T00:00:00.000Z', '"2021-09-11T23:59:59.000Z'],
['"2021-09-16T00:00:00.000Z', '"2021-09-11T23:59:59.000Z'],
['"2021-09-17T00:00:00.000Z', '"2021-09-11T23:59:59.000Z'],
['"2021-09-18T00:00:00.000Z', '"2021-09-18T23:59:59.000Z'],
]
I've already tried it with dayjs, this results in the array representing exact intervals from a particular date:
function getDates(date) {
var dates = [date]
var noOfDays = 7
for (let i = noOfDays - 1; i >= 0; i--) {
const elementIndex = i - noOfDays // Get last nth element of the list
const dateToIncrement = dates.slice(elementIndex)[0]
const newDate = dayjs(dateToIncrement).subtract(1, "day").toISOString()
dates.unshift(newDate)
}
return dates
}
Thank you
function getPastWeek(inputTime) {
var res = []; //result array
var currentDayEnd = undefined; //variable to be set on each iteration
var currentDay = new Date(inputTime.split('T')[0]); //create new Date object
currentDay.setDate(currentDay.getDate() - 7); //reduce seven days from current date
for(var i = 0; i <= 7; i++) { //foreach day in last week
currentDayEnd = new Date(currentDay.getTime() - 1000); //previous day end (1sec before current day start)
currentDayEnd.setDate(currentDayEnd.getDate() + 1); //current day end (one day after previous day end)
res.push([currentDay.toISOString(), currentDayEnd.toISOString()]); //append pair
currentDay.setDate(currentDay.getDate() + 1); //set variable to next day
}
return res;
}
var pastWeek = getPastWeek('2021-09-18T20:18:27.000Z'); //call example
The OP code is pretty close, you should have been able to adapt it to your needs. The following employs a similar algorithm. End of day is set to 1ms before midnight.
// Given a UTC ISO 8601 timestamp, return array of day plus
// previous 6 days with start of day, end of day timestmaps
function getDates(d) {
let s = new Date(d.slice(0,10));
let e = new Date(+s);
e.setUTCHours(23,59,59,999);
let result = [];
for (let i=7; i; i--) {
result.push([s.toISOString(), e.toISOString()]);
s.setUTCDate(s.getUTCDate() - 1);
e.setUTCDate(e.getUTCDate() - 1);
}
return result;
}
console.log(getDates(new Date().toISOString()));

Date Number increases wrong in JavaScript

I have a problem with creating a calendar in JavaScript. I want to display dates from Monday to Sunday. So this is my DateSet function:
dateSets(year) {
const today = new Date();
year = today.getFullYear();
let firstDayOfWeek = this.getDateOfWeek(this.currentWeekNumber, year);
let dates = [];
for (let i = 0; i < 7; i++) {
dates.push(
new Date(firstDayOfWeek.setDate(firstDayOfWeek.getDate() + i))
);
}
return dates;
}
getDateOfWeek(this.currentWeekNumber, year) gets the Monday of the week. But with this code displays 9/8/2021 10/8/2021 12/8/2021 15/8/2021 19/8/2021 24/8/2021 30/8/2021.
So when I change the i in the for with 1 it displays like this but I cannot use this because I cannot get Monday: 10/8/2021 11/8/2021 12/8/2021 13/8/2021 14/8/2021 15/8/2021 16/8/2021.

MomentJS getting previous dates relative to today

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.

Get all days of the week given a day

I'm trying to make a function to get all the days of the week given the current day. I had a function that i thought was working until i noticed that if the day of the week is near the end of the month, like for example February, i get weird data. Anyone know whats going on and how to fix it?
function days(current) {
var week = new Array();
// Starting Monday not Sunday
var first = ((current.getDate() - current.getDay()) + 1);
for (var i = 0; i < 7; i++) {
week.push(
new Date(current.setDate(first++))
);
}
return week;
}
var input = new Date(2017, 1, 27);
console.log('input: %s', input);
var result = days(input);
console.log(result.map(d => d.toString()));
.as-console-wrapper{min-height:100%}
If you don't want to use some kind of other library like Moment.js you can also change your function a little and then it will work. Try this:
function dates(current) {
var week= new Array();
// Starting Monday not Sunday
current.setDate((current.getDate() - current.getDay() +1));
for (var i = 0; i < 7; i++) {
week.push(
new Date(current)
);
current.setDate(current.getDate() +1);
}
return week;
}
console.log(dates(new Date(2017, 1, 27)));
You can use Moment.js library - utility library for dates/time operations
Here's examplary code to get current week's dates starting from monday:
function getThisWeekDates() {
var weekDates= [];
for (var i = 1; i <= 7; i++) {
weekDates.push(moment().day(i));
}
return weekDates;
}
var thisWeekDates = getThisWeekDates();
thisWeekDates.forEach(function(date){ console.log(date.format());});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.js"></script>
The code above prints following results to the console:
2017-03-20T21:26:27+01:00
2017-03-21T21:26:27+01:00
2017-03-22T21:26:27+01:00
2017-03-23T21:26:27+01:00
2017-03-24T21:26:27+01:00
2017-03-25T21:26:27+01:00
2017-03-26T21:26:27+02:00
I will trace your code using your example of Feb 27, 2017:
first = 27 - 1 + 1 = 27
loop:
Feb.setDate(27) = 27 feb
Feb.setDate(28) = 28 feb
Feb.setDate(29) = Not 29 days in Feb. So it sets current to 29-28 = 1st day of March
March.setDate(30) = March 30
March.setDate(31) = March 31
March.setDate(32) = Not 32 days in March. So it sets current to 31-32 = 1st of April..
April.setDate(33) = Not 33 days in April. So it sets current day 33-30 = 3rd day of May.
Please note that I used the shorthand of Month.setDate() to show the month of the current Date object when it was being called.
So the issue is with your understanding of setDate that is being used on current. It changes the month and if the value you use isn't a day in the month it adjusts the month and day appropriately. I hope this cleared things up for you.
For how to add one to a date, see Add +1 to current date. Adapted to your code, you can set current to the first day of the week then just keep adding 1 day and pushing copies to the array:
function days(current) {
var week = [];
// Starting Monday not Sunday
var first = current.getDate() - current.getDay() + 1;
current.setDate(first);
for (var i = 0; i < 7; i++) {
week.push(new Date(+current));
current.setDate(current.getDate()+1);
}
return week;
}
var input = new Date(2017, 1, 27);
console.log('input: %s', input);
var result = days(input);
console.log(result.map(d => d.toString()));
Note that this changes the date passed in (per the original code), you may want to make current a copy to avoid that.
Suppose monday starts the week, you can calculate monday and go to sunday. getDategives you the day of the week, and Sunday starts at 0. With momnday, we get just offset forward to 6 days to get sunday
mondayThisWeek(date: Date): Date {
const d = new Date(date)
const day = d.getDay()
const diff = d.getDate() - day + (day === 0 ? -6 : 1)
return new Date(d.setDate(diff))
}
const offsetDate = (base: Date, count: number): Date => {
const date = new Date(base)
date.setDate(base.getDate() + count)
return date
}
thisWeek(today: Date): TimeRange {
const monday = mondayThisWeek(today)
return {
startDate: monday,
endDate: offsetDate(monday, 6)
}
}
This can be achieved easly using moment
const getWeekDates = () => {
let weekDates = [];
for (let i = 0; i < 7; i++)
weekDates.push(moment().add(i, 'd'));
return weekDates;
};
console.log(getWeekDates());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.js"></script>

Get localized month name using native JS

It's possible to do this to get the localized full month name using native javascript.
var objDate = new Date("10/11/2009"),
locale = "en-us",
month = objDate.toLocaleString(locale, { month: "long" });
But this only gets the month number for a given date. I'd simply like to get the month name corresponding to a month number. For example, if I do getMonth(2) it would return February. How can I implement getMonth using native javascript(no libraries like moment)?
You are already close:
var getMonth = function(idx) {
var objDate = new Date();
objDate.setDate(1);
objDate.setMonth(idx-1);
var locale = "en-us",
month = objDate.toLocaleString(locale, { month: "long" });
return month;
}
console.log(getMonth(1));
console.log(getMonth(12));
To get all the months of a year and days of the week, loop over a set of dates and use toLocaleString with appropriate options to get the required values:
function getLocalDayNames() {
let d = new Date(2000,0,3); // Monday
let days = [];
for (let i=0; i<7; i++) {
days.push(d.toLocaleString('default',{weekday:'long'}));
d.setDate(d.getDate() + 1);
}
return days;
}
console.log(getLocalDayNames());
function getLocalMonthNames() {
let d = new Date(2000,0); // January
let months = [];
for (let i=0; i<12; i++) {
months.push(d.toLocaleString('default',{month:'long'}));
d.setMonth(i + 1);
}
return months;
}
console.log(getLocalMonthNames());
The language default means toLocaleString uses the default language of the implementation that the code is running in.

Categories

Resources