- miguelmota / getDates.js
- Help me sir, how to check between two date range. Example
- How To Create Date Range In Javascript (Simple Examples)
- TLDR – QUICK SLIDES
- TABLE OF CONTENTS
- DOWNLOAD & NOTES
- QUICK NOTES
- EXAMPLE CODE DOWNLOAD
- DATE RANGE
- 1) DATE RANGE BETWEEN START & END
- 2) LAST/NEXT N DAYS
- EXTRA BITS & LINKS
- LINKS & REFERENCES
- INFOGRAPHIC CHEAT SHEET
- THE END
- Leave a Comment Cancel Reply
- Search
- Breakthrough Javascript
- Socials
- About Me
- How to get the date range between the two dates using moment.js?
miguelmota / getDates.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
// Returns an array of dates between the two dates |
function getDates ( startDate , endDate ) |
const dates = [ ] |
let currentDate = startDate |
const addDays = function ( days ) |
const date = new Date ( this . valueOf ( ) ) |
date . setDate ( date . getDate ( ) + days ) |
return date |
> |
while ( currentDate <= endDate ) |
dates . push ( currentDate ) |
currentDate = addDays . call ( currentDate , 1 ) |
> |
return dates |
> |
// Usage |
const dates = getDates ( new Date ( 2013 , 10 , 22 ) , new Date ( 2013 , 11 , 25 ) ) |
dates . forEach ( function ( date ) |
console . log ( date ) |
> ) |
My version which strips hours, minutes, seconds etc. and does not declare an inline function:
// Returns an array of dates between the two dates const getDatesBetween = (startDate, endDate) => const dates = []; // Strip hours minutes seconds etc. let currentDate = new Date( startDate.getFullYear(), startDate.getMonth(), startDate.getDate() ); while (currentDate endDate) dates.push(currentDate); currentDate = new Date( currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate() + 1, // Will increase month if over range ); > return dates; >; // Usage const dates = getDates(new Date(2018, 0, 30, 11, 30), new Date(2018, 2, 2, 23, 59, 59)); console.log(dates);
Thanks @aalexgabi, it resolved my problem 💯
Help me sir,
how to check between two date range.
Example
from date=03-07-2018
to date=13-07-2018
how to check date range between them in javascript
@sibelius can you elaborate on how you use that function? For instance, it looks like you have another file you are including. What does that look like? Thanks in advance!
Please i would need help, i would like to do this using two date time picker and insert the dates in between the date time picker in a database but i dont know how to go about this in vb.net. Someone should help me please
I made something more generic
it uses date-fns and does not mutate the array
import < addDays, addMonths, differenceInDays, differenceInMonths >from 'date-fns'; import < PERIOD >from './PeriodEnumType'; export function dateRange(startDate, endDate, interval) < if (interval === PERIOD.DAY) < const days = differenceInDays(endDate, startDate); return [. Array(days+1).keys()].map((i) =>addDays(startDate, i)); > if (interval === PERIOD.MONTH) < const months = differenceInMonths(endDate, startDate); return [. Array(months+1).keys()].map((i) =>addMonths(startDate, i)); > >
Can u help using two date time picker and insert the dates in a database in vb.net
Here’s a function to get a range of dates, split up by any key, ex. month, day, year, etc.
const moment = require('moment'); function getRangeOfDates(start, end, key, arr = [start.startOf(key)])
So if I wanted to get an array of months from the start of the year until a year from now, I would go:
const begin = moment().startOf('year') const end = moment().add(1, 'year') getRangeOfDates(begin, end, 'month');
[ moment("2017-01-01T00:00:00.000"), moment("2017-02-01T00:00:00.000"), moment("2017-03-01T00:00:00.000"), moment("2017-04-01T00:00:00.000"), moment("2017-05-01T00:00:00.000"), moment("2017-06-01T00:00:00.000"), moment("2017-07-01T00:00:00.000"), moment("2017-08-01T00:00:00.000"), moment("2017-09-01T00:00:00.000"), moment("2017-10-01T00:00:00.000"), moment("2017-11-01T00:00:00.000"), moment("2017-12-01T00:00:00.000"), moment("2018-01-01T00:00:00.000"), moment("2018-02-01T00:00:00.000"), moment("2018-03-01T00:00:00.000"), moment("2018-04-01T00:00:00.000"), moment("2018-05-01T00:00:00.000"), moment("2018-06-01T00:00:00.000"), moment("2018-07-01T00:00:00.000"), moment("2018-08-01T00:00:00.000"), moment("2018-09-01T00:00:00.000") ]
It works but I have a problem with the month.
I run it like that:
var dates = getDates(new Date(2019,04,16), new Date(2019,04,17)); dates.forEach(function(date) < console.log(date); >);
Thu May 16 2019 00:00:00 GMT+0300 (Israel Daylight Time)
Fri May 17 2019 00:00:00 GMT+0300 (Israel Daylight Time)
I received May instead of April, why? What am I missing?
Hi @nivduran. When using the Date constructor like that:
new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);
keep in mind that the monthIndex parameter is 0-based. This means that January = 0 and December = 11.
In your case, you used 4 as the monthIndex parameter, which means the fifth month of the year which is May.
How about filling missing dates inside arrays
Actually very useful for charts that has missing data.
if you are looking for specific days of the week this will give them to you granted you provide a string array, otherwise, just dont use the if statement .
import * as moment from "moment"; import * as _ from 'lodash'; getDatesOfDays(startDate: moment.Moment, endDate: moment.Moment, dayArray: string[]) < var range = []; var dayNames = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']; while (moment(startDate) startDate.add(1 , 'days'); > return range; >
get days diff between two dates and output all weekdays in between including start and end dates.
return an array of dates.
const moment = require("moment"); const getDatesDiff = (start_date, end_date, date_format = "YYYY-MM-DD") => const getDateAsArray = date => return moment(date.split(/\D+/), date_format); >; const diff = getDateAsArray(end_date).diff(getDateAsArray(start_date), "days") + 1; const dates = []; for (let i = 0; i diff; i++) const nextDate = getDateAsArray(start_date).add(i, "day"); const isWeekEndDay = nextDate.isoWeekday() > 5; if (!isWeekEndDay) dates.push(nextDate.format(date_format)) > return dates; >;
const date_log = getDaysDiff ('2019-10-17', '2019-10-25'); console.log(date_log);
date_log = [ '2019-10-17', '2019-10-18', '2019-10-21', '2019-10-22', '2019-10-23', '2019-10-24', '2019-10-25' ]
I tried this and it was returned wrong
getDates(new Date(2019,12,22), new Date(2020,1,7));
Wed Jan 22 2020 00:00:00 GMT+0700 (Indochina Time) Thu Jan 23 2020 00:00:00 GMT+0700 (Indochina Time) Jan 24 2020 00:00:00 GMT+0700 (Indochina Time) Sat Jan 25 2020 00:00:00 GMT+0700 (Indochina Time) Sun Jan 26 2020 00:00:00 GMT+0700 (Indochina Time) Mon Jan 27 2020 00:00:00 GMT+0700 (Indochina Time) Tue Jan 28 2020 00:00:00 GMT+0700 (Indochina Time) Wed Jan 29 2020 00:00:00 GMT+0700 (Indochina Time) Thu Jan 30 2020 00:00:00 GMT+0700 (Indochina Time) Fri Jan 31 2020 00:00:00 GMT+0700 (Indochina Time) Sat Feb 01 2020 00:00:00 GMT+0700 (Indochina Time) Sun Feb 02 2020 00:00:00 GMT+0700 (Indochina Time) Mon Feb 03 2020 00:00:00 GMT+0700 (Indochina Time) Tue Feb 04 2020 00:00:00 GMT+0700 (Indochina Time) Wed Feb 05 2020 00:00:00 GMT+0700 (Indochina Time) Thu Feb 06 2020 00:00:00 GMT+0700 (Indochina Time) Fri Feb 07 2020 00:00:00 GMT+0700 (Indochina Time)
How To Create Date Range In Javascript (Simple Examples)
Welcome to a tutorial on how to create a date range in Javascript. Need to create a range of dates in Javascript? No worries, it is actually pretty easy.
- Parse the start and end dates into date objects.
- var start = new Date(«1 Feb 2020»);
- var end = new Date(«28 Feb 2020»);
- Get the Unix Timestamps of both start and end dates.
- var ustart = start.getTime();
- var uend = end.getTime();
- Lastly, loop through the timestamps to create the date range.
- for (unix = ustart; unix
That should cover the basics, but read on for more examples!
ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.
TLDR – QUICK SLIDES
TABLE OF CONTENTS
DOWNLOAD & NOTES
Firstly, here is the download link to the example code as promised.
QUICK NOTES
If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.
EXAMPLE CODE DOWNLOAD
Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
DATE RANGE
All right, let us now get into the examples of how to create a date range in Javascript.
1) DATE RANGE BETWEEN START & END
// (A) CREATE DATE RANGE FUNCTION function dateRange (start, end) < // (A1) EMPTY DATE RANGE + PARSE INTO DATE OBJECTS var range = [], start = new Date(start), end = new Date(end); // (A2) CREATE RANGE BY LOOPING THROUGH IN UNIX TIMESTAMP // 1 DAY = 24 HRS * 60 MINS * 60 SECS * 1000 MS = 86400000 for (let unix = start.getTime(); unix // (A3) RETURN RESULTS return range; > // (B) TEST var range = dateRange("1 Feb 2003", "28 Feb 2003"); console.log(range);
Look no further, this is doing the same thing as the snippet in the introduction – Except that it is “packaged” into a function. Simply plug the start and end date into dateRange() , and it returns the date range in an array.
2) LAST/NEXT N DAYS
// (A) LAST/NEXT DAYS function daysRange (dstart, offset, direction) < // (A1) PARSE INTO DATE OBJECT let start = new Date(dstart), end = new Date(dstart); // (A2) OFFSET END DATE if (direction) < end.setDate(end.getDate() + offset); >else < start.setDate(start.getDate() - offset); >// (A3) CREATE DATE RANGE let range = []; for (let unix = start.getTime(); unix < end.getTime(); unix += 86400000) < // (A3-1) UNIX TIMESTAMP TO DATE let thisDay = new Date(unix); range.push(thisDay); // (A3-2) FORMAT IF REQUIRED // range.push(thisDay.toLocaleDateString("en-GB")); >// (A4) RETURN RESULTS return range; > // (B) TEST // (B1) 7 DAYS FROM "1 FEB 2003" var range = daysRange("1 Feb 2003", 7, true); console.log(range); // (B2) 14 DAYS BEFORE "3 APR 2005" range = daysRange("3 Apr 2005", 14, false); console.log(range);
- dstart The starting date.
- offset Number days offset.
- direction True for “next N days from starting date”, false for “last N dates from starting date”.
That’s all the calculations are pretty much the same, based on looping through the Unix Timestamp.
EXTRA BITS & LINKS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
LINKS & REFERENCES
INFOGRAPHIC CHEAT SHEET
THE END
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!
Leave a Comment Cancel Reply
Search
Breakthrough Javascript
Take pictures with the webcam, voice commands, video calls, GPS, NFC. Yes, all possible with Javascript — Check out Breakthrough Javascript!
Socials
About Me
W.S. Toh is a senior web developer and SEO practitioner with over 20 years of experience. Graduated from the University of London. When not secretly being an evil tech ninja, he enjoys photography and working on DIY projects.
Code Boxx participates in the eBay Partner Network, an affiliate program designed for sites to earn commission fees by linking to ebay.com. We also participate in affiliate programs with Bluehost, ShareASale, Clickbank, and other sites. We are compensated for referring traffic.
How to get the date range between the two dates using moment.js?
In this article, we are going to implement the logic to get the date range between the two dates using moment js and plain javascript. In other words, we are going to find the list of dates that come between the two dates.
If you have not created the project, then please create a folder and call it “daterange”. Open the folder and create a file called index.js. Now it’s time to import moment.js into the project. You can achieve this by 2 methods.
- By including the moment.js file inside the script tag. For this, you would need an HTML file, let’s call it index.html. If you are going by this method, then please create an HTML file inside the root folder, i.e., daterange. The base content of this file would be something like this –
let moment = require('moment'); //Include moment in your JS file
We are done with the basic setup. Now it’s time to write the code to get the date range between the two dates. Here is the code snippet –
let moment = require('moment'); //Include moment in your JS file let dateArr = []; //Array where dates will be stored let fromDate = new Date(moment().format('MM-DD-YYYY')); //From Date //Let's assume the endDate to be 15 days later from today let endDate = new Date(moment().add(15, 'days').format('MM-DD-YYYY')); //Logic for getting rest of the dates between two dates("FromDate" to "EndDate") while(fromDate < endDate)< dateArr.push(moment(fromDate).format('ddd DD-MM')); let newDate = fromDate.setDate(fromDate.getDate() + 1); fromDate = newDate(newDate); >//Print all dates console.log(dateArr)
If you want to use this in index.html, then include this inside the tag and run this file in the browser.
That’s it. This will return the list of the rest of the dates that lie between the two given dates. Hope you get the desired output. Happy coding 🙂
Do comment below if you are still facing any issues. Happy to help. Thanks.