Generate an array of weeks since 2017 till now using moment.js - javascript

I need to list week array from 2017 till now. My week start from Monday and ends with Sunday I tried to do in moment.js,
const startDate = moment().isoWeekday('Monday').format('DD-MM-YYYY');
const endDate = moment().isoWeekday('Sunday').format('DD-MM-YYYY');
I tried to like this to get the week start date and end date but I don't know the process to next step.
Note my array list start with ["02-01-2017", "08-01-2017"] and ends with current week will be the Last one.
const result = [["02-01-2017", "08-01-2017"],...... ["05-01-2018", "11-01-2018"]]

You can initialize your start date to 1st weekday of 1st January 2017 and iterate to all the dates less than today and keep adding days in an array.
var weeks = [];
var startDate = moment(new Date(2017,0,1)).isoWeekday(8);
if(startDate.date() == 8) {
startDate = startDate.isoWeekday(-6)
}
var today = moment().isoWeekday('Sunday');
while(startDate.isBefore(today)) {
let startDateWeek = startDate.isoWeekday('Monday').format('DD-MM-YYYY');
let endDateWeek = startDate.isoWeekday('Sunday').format('DD-MM-YYYY');
startDate.add(7,'days');
weeks.push([startDateWeek,endDateWeek]);
}
console.log(weeks)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>

Something like that would help?
let startDate = moment('2017-01-01').startOf('week').format('YYYY-MM-DD');
let endDate = moment(new Date()).startOf('week').format('YYYY-MM-DD');
const weeks = [];
while (startDate <= endDate) {
weeks.push(startDate);
startDate = moment(startDate).add(7, 'days').format('YYYY-MM-DD');
}
console.log('weeks:', weeks);

Related

Display year to date

I am trying to display data for a "Year to Date" range. I need it to show all the dates ranging from the first day of January 2021 until the current date (whatever day today is).
I previously had the data showing only the previous 30 days and had:
const today = new Date();
const startDate =
this.startDate || new Date(today.getFullYear(), today.getMonth(), today.getDate() - 30);
const endDate = this.endDate || today;
How can I get the data to show from January 1st, 2021 to whatever the current day is?
Here is how to create an array dateArray of all dates between the first of this year and today:
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
const today = new Date()
const startDate = new Date(today.getFullYear(), 0, 1);
var dateArray = new Array();
var currentDate = startDate;
while (currentDate <= today) {
dateArray.push(new Date(currentDate));
currentDate = currentDate.addDays(1);
}
console.log(dateArray)
This will work for every current year
const aDay = 24*60*60*1000;
const end = new Date()
// normalise - otherwise I would see last day of previous year until yesterday due to timezones
end.setHours(15,0,0,0);
const start = new Date(end.getFullYear(),0,0,15,0,0,0); // 31/12/previous year to get date 0
const days = (end.getTime()-start.getTime())/aDay
let t = start.getTime();
const dates = [...Array(days)] // create an array of days
.map(() => new Date(t+=aDay).toISOString().split('T')[0])
console.log(dates)
Using while
const aDay = 24*60*60*1000;
const end = new Date()
// normalise - otherwise I would see last day of previous year until yesterday due to timezones
end.setHours(15,0,0,0);
const start = new Date(end.getFullYear(),0,0,15,0,0,0); // 31/12/previous year to get date 0
const days = (end.getTime()-start.getTime())/aDay
let t = start.getTime();
const endTime = end.getTime();
const dates = [];
while (t<endTime) {
dates.push(new Date(t+=aDay).toISOString().split('T')[0])
}
console.log(dates)
As others have answered, just "better" — IMHO of course. :-)
// Default end is current date
function getDateRange(startDate, endDate = new Date()) {
// Default start to 1 Jan of endDate year
if (!startDate) {
startDate = new Date(endDate.getFullYear(), 0);
// Otherwise copy startDate so don't affect original
} else {
startDate = new Date(+startDate);
}
let result = [];
// Push timestamps into an array until endDate
while (startDate <= endDate) {
// Push date in YYYY-MM-DD format into result array
result.push(startDate.toLocaleDateString('en-CA'));
// Increment startDate
startDate.setDate(startDate.getDate() + 1);
}
return result;
}
// Dates from 1 Jan to today
console.log(getDateRange());

How to get full day hour date format in node js

Hi I want to print a list of today date starting with 0th hour till 24 hour
const date = new Date().toISOString();
console.log(date) //21-06-01T17:09:40.766Z
the above code gives me current ISO dateTimestamp
I want dateTimestamp staring from 21-06-01T00:00:00Z,........,21-06-01T24:00:00Z
How to get that any simple way is available
This is how you do it using only JavaScript:
var currentTimeStamp = new Date().getTime() // get current timestamp
var firstTime = (currentTimeStamp - (currentTimeStamp % 86400000)) // get the first hour of the day
var totalMilliSecsInHour = 3600000 // milliseconds in one hour
for (let i = 0; i < 24; i++) {
console.log(new Date(firstTime))
firstTime += totalMilliSecsInHour // after getting the date increment the timestamp
}
You can do it with luxon.
First get the first hour of the day, then only sum one hour until 24.
import { DateTime } from 'luxon';
const allHours = []; // Array of hours
const fistHour = DateTime.utc().startOf('day'); // this is the 00:00
const totalHours = 24;
let currentHour = 0;
for (currentHour = 0; currentHour < totalHours; currentHour++) {
const startHourDT = fistHour.plus({ hours: currentHour });
allHours.push(startHourDT.toJSDate());
}
console.log(allHours);
Dont forget instal Luxon fist with npm i luxon --save.
Hope it help you
PS. I don speak english very well.

List different subrange days from a date range with moment and javascript

I have 2 dates with hours:
Start: 2019-09-06 14:00:00
End: 2019-09-9 19:30:00
I need to list all subrange days (full or partial) inside the range, also with hours, in this example:
2019-09-06 14:00:00 to 2019-09-06 23:59:59
2019-09-07 00:00:00 to 2019-09-07 23:59:59
2019-09-08 00:00:00 to 2019-09-08 23:59:59
2019-09-09 00:00:00 to 2019-09-09 19:30:00
in an array like:
result = array(
0 => array(
"Start" => 2019-09-06 14:00:00,
"End" => 2019-09-06 23:59:59
),
1 => array(
"Start" => 2019-09-07 00:00:00,
"End" => 2019-09-07 23:59:59
),
...
)
I have found similar script to list all days like:
var enumerateDaysBetweenDates = function(startDate, endDate) {
var dates = [];
var currDate = moment(startDate).startOf('day');
var lastDate = moment(endDate).startOf('day');
while(currDate.add(1, 'days').diff(lastDate) < 0) {
console.log(currDate.toDate());
dates.push(currDate.clone().toDate());
}
return dates;
};
But it doesn't consider hour and subrange like I need.
I'd like to use moment.js to simplify all the job but i'm not sure how to start with.
Any suggest how to "recognize" different days?
That was a fun exercise with moment.js. The idea is to collect list of day starts and ends separately:
var start = "2019-09-06 14:00:00";
var end = "2019-09-9 19:30:00";
var startMoment = moment(start);
var endMoment = moment(end);
var starts = [startMoment.toDate()];
var ends = [];
var dayBeforeEnd = moment(endMoment).subtract(1, 'days');
for (var m = moment(startMoment); m.isBefore(dayBeforeEnd); m.add(1, 'days')) {
ends.push(moment(m).endOf('day').toDate());
starts.push(moment(m).add(1, 'days').startOf('day').toDate());
}
ends.push(endMoment.toDate());
Now starts[i] and ends[i] contains corresponding day start and end as Date objects.
One may notice a lot of moment(moment_object) happening. That is because moment objects are mutable, so you need to clone it every time you need to add or subtract some timerange.
You don't need to load moment for that.
In JavaScript, the Date object has setHour(), setMinutes() and so on. You can get the current date, sum 24 hours and get the date again.
For example:
function getRanges(start, end) {
start = new Date(start).getTime(); // Sanitize input
end = new Date(end).getTime();
var list = [];
var current = start;
while(current < end) {
var date = new Date(current); // Get current date
// Set the date to just before midnight.
date.setHours(23);
date.setMinutes(59);
date.setSeconds(59);
date.setMilliseconds(999);
// Now you have the next element in the range
var next = date.getTime();
if (next > end) { // Don't surpass the end
next = end;
}
// create a range using the current and the end of the day before midnight
list.push({
start: current,
end: next
});
current = next+1; // Go to the very next day
}
return list;
}
var ranges = getRanges(Date.now()-(7*24*60*60*1000), Date.now());
// You can convert them to dates if you want
for (var i = 0; i < ranges.length; i++) {
ranges[i].start = new Date(ranges[i].start).toLocaleString();
ranges[i].end = new Date(ranges[i].end).toLocaleString();
}
console.log(ranges);

Get date/times between two Moment date/times

I am using Node.JS and the excellent Moment library. I have a function that needs to generate an agenda of future dates (like an appointment system)
I have two timestamps representing the start and end of a period of time.
I want to create an array of date/times between these two times, dependent on a specific day and time of that day.
An example would be:
START DATE: 2019-01-26 15:00:01 (Saturday)
END DATE: 2019-02-23 15:00:00 (also a Saturday)
WE NEED: EVERY SATURDAY # 1500
EXPECTED ARRAY:
2019-02-02 15:00:00
2019-02-09 15:00:00
2019-02-16 15:00:00
2019-02-23 15:00:00
Please note: The start is not included in the array because it is later (by one second) than what we are looking for.
Any idea on how to accomplish this in Node?
const moment = require('moment')
const formatDate = date => moment(date).format('MMMM Do YYYY, h:mm:ss a')
const START_DATE = '2019-01-26 15:00:00'
const END_DATE = '2019-02-23 15:00:00'
let current = formatDate(START_DATE)
const end = formatDate(END_DATE)
let days = 7
let result = []
while (current > end) {
current = moment(START_DATE).add(days, 'days')
current = formatDate(current)
result.push(current)
days += 7
}
result.push(end)
result.forEach(date=>console.log(date))
import moment from 'moment';
const getDaysBetween = (startDate, endDate, day, time) => {
// Define a first day of result
let firstDay = moment(startDate)
.day(day)
.set('hour', time.match(/[\d]+(?=:)/g)[0])
.set('minutes', time.match(/(?<=:)[\d]+/g)[0])
.set('seconds', 0);
let resultDates = [ firstDay ];
// Add the rest
let weekBetweenThese = endDate.diff(firstDay, 'week');
Array(weekBetweenThese).fill({}).forEach((d, i) => {
resultDates.push(moment(firstDay).add(i + 1, 'weeks'))
});
// Filter out somecase that result day match with startDate & endDate but time condition goes wrong
resultDates = resultDates.filter(resultDate =>
startDate <= resultDate &&
resultDate <= endDate
);
return resultDates.map(resultDate => resultDate.toDate());
// return resultDates; // Return array of moment date.
};
console.log(
getDaysBetween(
moment('2019-01-26 15:00:01'),
moment('2019-02-23 15:00:00'),
'Saturday', '15:00'
)
)
https://codesandbox.io/s/wkpz72mo9w

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>

Categories

Resources