get month range using new Date() - javascript

function firstDayOfMonth(given_month) {
var d = new Date();
d.setMonth(given_month, 1);
return d.toISOString();
}
function lastDayOfMonth(given_month) {
var d = new Date();
d.setMonth(given_month + 1, 0);
return d.toISOString();
}
var temp = {
firstDayOfMonth: firstDayOfMonth(given_month),
lastDayOfMonth: lastDayOfMonth(given_month)
}
console.log(JSON.stringify(temp))
Trying to get first day of the month and last day of the month to develop a monthly report. I got {"firstDayOfMonth":"2016-11-01T09:45:30.998Z","lastDayOfMonth":"2016-11-30T09:45:30.998Z"}
for temp, is that normal? why it's 9:45 something?

You are doing the right thing. You just need to set hour for start and end day:
firstDayOfMonth.setHours(0,0,0,0);
lastDayOfMonth.setHours(23,59,59,999);

Just normalize date object with H/M/S set to 12:00:00, like this:
const givenMonth = 6;
const normalizeTime = d => {
d.setHours(12);
d.setMinutes(0);
d.setSeconds(0);
return d;
};
const getISODate = (month, day) => {
const d = new Date();
d.setMonth(month, day);
return normalizeTime(d).toISOString();
};
const temp = {
firstDayOfMonth: getISODate(givenMonth, 1),
lastDayOfMonth: getISODate(givenMonth + 1, 0)
};
temp;

Related

create array of array of datepairs that have gap of n days between them

Consider 2 dates, format will be MM/DD/YYYY
1st date = today
2nd date = 45 days from today
Note: Here, the 1st date and 2nd date are variable.
i.e. 1st date that is today can be tomorrow or any other date. 2nd date can be 15 days, 24 days, 105 days i.e. this "n" can also vary.
Assuming the above 2 dates as startDate and stopDate. I want to create array of datePairs of a given gap between them.
For e.g. if startDate = 12/01/2022 & stopDate = 12/20/2022. I want to have datePairs having gap of 2 (n = 2) days between them. So, the output array should look like
[
['12/01/2022', '12/03/2022'],
['12/04/2022', '12/06/2022'],
['12/07/2022', '12/09/2022'],
['12/10/2022', '12/12/2022'],
['12/13/2022', '12/15/2022'],
['12/16/2022', '12/18/2022'],
['12/19/2022', '12/20/2022']
]
NOTE: Here, the last array does not have the gap of 2 dates because it's just 1 day away from the stopDate. In such case, the last pair can have less gap between them.
The only condition is the above array length should always be even.
Date.prototype.addDays = function (days) {
var dat = new Date(this.valueOf());
dat.setDate(dat.getDate() + days);
return dat;
};
function splitInto(array, size, inplace) {
var output, i, group;
if (inplace) {
output = array;
for (i = 0; i < array.length; i++) {
group = array.splice(i, size);
output.splice(i, 0, group);
}
} else {
output = [];
for (i = 0; i < array.length; i += size) {
output.push(array.slice(i, size + i));
}
}
return output;
}
function getDates(startDate, stopDate) {
var dateArray = new Array();
var currentDate = startDate;
var i = 0;
while (currentDate <= stopDate) {
if (i % 2 == 1) {
const options = {
year: 'numeric'
};
options.month = options.day = '2-digit';
var formattedCSTDate = new Intl.DateTimeFormat([], options).format(currentDate);
dateArray.push(formattedCSTDate);
currentDate = currentDate.addDays(1);
} else {
const options = {
year: 'numeric'
};
options.month = options.day = '2-digit';
var formattedCSTDate = new Intl.DateTimeFormat([], options).format(currentDate);
dateArray.push(formattedCSTDate);
currentDate = currentDate.addDays(3);
}
i = i + 1;
}
return dateArray;
};
var dateArray = getDates(new Date(), (new Date()).addDays(43));
var datePairLength = 2;
var rangeArray = splitInto(dateArray, datePairLength, false);
console.log(rangeArray);
It seems to me you're making it more complicated than it needs to be. Just build each range as an array and avoid the splitInto function. You might use a date library (there are many to chose from) for adding days and formatting:
function makeRanges(start = new Date(), end = new Date(), interval = 1) {
let f = new Intl.DateTimeFormat('default', {
year:'numeric',month:'short',day:'2-digit'
});
let s = new Date(start);
let ranges = [];
while (s < end) {
let t = new Date(s);
t.setDate(t.getDate() + interval);
ranges.push([f.format(s), t < end? f.format(t) : f.format(end)]);
s.setDate(s.getDate() + interval + 1)
}
return ranges;
}
console.log(
makeRanges(new Date(2022,0,1), new Date(2022,1,1), 2)
);

Fill in empty blocks for each calendar month JS

I am currently able to fetch the given days of the current month as well as previous and future months using JS. What I would like to achieve, is if say December starts on a Tuesday I would like to pass in empty objects for Sunday and Monday. December also ends on a Thursday, so I would like to pass in empty objects for Friday and Saturday.
The code I am currently using to fetch each calendar month and display them is as follows:
import React, { useEffect, useState, useCallback } from "react";
import "./styles.css";
export default function App() {
const [visibleMonth, setVisibleMonth] = useState(new Date().getMonth());
const [calData, setCalData] = useState(null);
const [dates, setDates] = useState(null);
const getDaysArray = async (s, e) => {
let a = [];
for (let d = new Date(s); d <= e; d.setDate(d.getDate() + 1)) {
a.push(new Date(d).toString());
}
return a;
};
const currentMonth = useCallback(async () => {
let d = new Date();
d.setMonth(visibleMonth);
let firstDay = new Date(d.getFullYear(), d.getMonth(), 1);
let lastDay = new Date(firstDay.getFullYear(), firstDay.getMonth() + 1, 0);
let calendarMonth = d.toLocaleString("en-us", {
month: "long",
year: "numeric"
});
setCalData(calendarMonth);
const dates = await getDaysArray(firstDay, lastDay);
setDates(dates);
}, [visibleMonth]);
useEffect(() => {
currentMonth();
}, [currentMonth]);
const prevMonth = async () => {
let d = new Date();
d.setMonth(visibleMonth - 1);
setVisibleMonth((state) => visibleMonth - 1);
let firstDay = new Date(d.getFullYear(), d.getMonth(), 1);
let lastDay = new Date(firstDay.getFullYear(), firstDay.getMonth() + 1, 0);
let calendarMonth = d.toLocaleString("en-us", {
month: "long",
year: "numeric"
});
setCalData(calendarMonth);
const dates = await getDaysArray(firstDay, lastDay);
setDates(dates);
};
const nextMonth = async () => {
let d = new Date();
d.setMonth(visibleMonth + 1);
setVisibleMonth((state) => visibleMonth + 1);
let firstDay = new Date(d.getFullYear(), d.getMonth(), 1);
let lastDay = new Date(firstDay.getFullYear(), firstDay.getMonth() + 1, 0);
let calendarMonth = d.toLocaleString("en-us", {
month: "long",
year: "numeric"
});
setCalData(calendarMonth);
const dates = await getDaysArray(firstDay, lastDay);
setDates(dates);
};
return (
<div className="App">
<h1>{calData}</h1>
<button onClick={prevMonth}>Prev Month</button>
<button onClick={nextMonth}>Next Month</button>
{dates &&
dates.map((item, i) => {
return <div key={i}>{item}</div>;
})}
</div>
);
}
the reason I am attempting to do so is due to the grid I have created. As it stands now, every month starts at sunday and I am not successfully pairing the correct days of the month with the days on the calendar. For example december starts on a tuesday, yet my styling shows it starts on a sunday any help would be greatly appreciated. the console logs currently show the days each month should start and end on.
Attached is a code pen for debugging! https://codesandbox.io/s/heuristic-visvesvaraya-r9lcw?file=/src/App.js
Based upon your most recent comments and updates, I recommend the following changes to the getDaysArray() method:
Create the d date outside the loop in order to use getDay() (day of week #)
Fill the a[] with empty strings with the number of day of week # in a for loop
Finally, populate the date strings into the remainder of the a[] array.
That should do it:
const getDaysArray = async (s, e) => {
let a = [];
let d = new Date(s);
let emptyCount = d.getDay();
for(let i = 0; i < emptyCount; i++) {
a.push('');
}
for (d; d <= e; d.setDate(d.getDate() + 1)) {
a.push(new Date(d).toString());
}
return a;
};

JavaScript: How to get simple date without timezone

I have code that generates random dates in a date range, which gives me dates which, when logged, produce this format:
Wed Sep 25 2019 05:00:00 GMT+0500 (Pakistan Standard Time)
I just want to get the date without timezone and Day specifically like this:
2019-09-25
I am trying to get random dates between specified dates using the following code:
var startDate = new Date("2019-08-26"); //YYYY-MM-DD
var endDate = new Date("2019-09-25"); //YYYY-MM-DD
var getDateArray = function(start, end) {
var arr = new Array();
var dt = new Date(start);
while (dt <= end) {
arr.push(new Date(dt));
dt.setDate(dt.getDate() + 1);
}
return arr;
}
var dateArr = getDateArray(startDate, endDate);
function shuffle(arra1) {
var ctr = arra1.length, temp, index;
// While there are elements in the array
while (ctr > 0) {
// Pick a random index
index = Math.floor(Math.random() * ctr);
// Decrease ctr by 1
ctr--;
// And swap the last element with it
temp = arra1[ctr];
arra1[ctr] = arra1[index];
arra1[index] = temp;
}
return arra1; }
console.log(shuffle(dateArr));
It's not a duplicate question as I was trying to achieve different and very specific formate.
One solution would be to map each item of arra1 through a custom formating function (ie formatDate()) where .getDate(), .getMonth() and .getYear() are used to populate the formatted string:
function formatDate(date) {
const year = date.getFullYear();
/* getMonth returns dates from 0, so add one */
const month = date.getMonth() + 1;
const day = date.getDate();
return `${year}-${month < 10 ? '0' : ''}${ month }-${ day < 10 ? '0' : '' }${day}`
}
Some points to consider here are:
Date#getMonth() returns 0-indexed dates in the range of 0-11. To match the desired date format, you should add 1 as shown
Check for day and month values that are less than 10 and prefix a 0 to pad those numbers to obtain the desired formatting
This can be added to your existing code as shown:
var startDate = new Date("2019-08-26"); //YYYY-MM-DD
var endDate = new Date("2019-09-25"); //YYYY-MM-DD
function formatDate(date) {
const year = date.getFullYear();
/* getMonth returns dates from 0, so add one */
const month = date.getMonth() + 1;
const day = date.getDate();
return `${year}-${month < 10 ? '0' : ''}${ month }-${ day < 10 ? '0' : '' }${day}`
}
var getDateArray = function(start, end) {
var arr = new Array();
var dt = new Date(start);
while (dt <= end) {
arr.push(new Date(dt));
dt.setDate(dt.getDate() + 1);
}
return arr;
}
var dateArr = getDateArray(startDate, endDate);
function shuffle(arra1) {
var ctr = arra1.length,
temp, index;
// While there are elements in the array
while (ctr > 0) {
// Pick a random index
index = Math.floor(Math.random() * ctr);
// Decrease ctr by 1
ctr--;
// And swap the last element with it
temp = arra1[ctr];
arra1[ctr] = arra1[index];
arra1[index] = temp;
}
/* Update this line */
return arra1.map(formatDate);
}
console.log(shuffle(dateArr));
Use .toISOString() and .substr(). Example:
var dt = new Date("2019-09-25");
console.log(dt.toISOString().substr(0,10)); // 2019-09-25
The advantage of this approach is that the Date object has the .toISOString() method built-in, so you don't have to reinvent the wheel. That method returns a full ISO string, though, like "2019-09-25T00:00:00.000Z". So, you can use .substr to retrieve only the part you want to use.
var getDates = function(startDate, endDate) {
var dates = [],
currentDate = startDate,
addDays = function(days) {
var 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
var dates = getDates(new Date(2019, 10, 22),
new Date(2019, 11, 25));
dates.forEach(function(date) {
console.log(date);
});

how to get weeks in particular month with dates in java script

This is my code
const date = new Date();
const startDate = new Date(date.getFullYear(), date.getMonth(), 1);
const endDate = new Date(date.getFullYear(), date.getMonth() + 1, 0);
const getDateArray = function(start, end) {
const arr = [];
const dt = new Date(start);
while (dt <= end) {
arr.push(new Date(dt));
dt.setDate(dt.getDate() + 1);
}
return arr;
}
const dateArr = getDateArray(startDate, endDate);
in this above code I got the current month date list dateArr, Now I need to group the days by a week, from the week list I need to filter only week start date and weekend date that must be in list formate I tried with the above code but I cant proceed to next.
This works.
var date = new Date();
console.log("All Weeks : ", getWeeksInaMonth())
console.log("Current Week : ", getCurrentWeek())
console.log("Current and previous weeks : ",getCurrAndPrevWeeks())
function getFormattedDate(dateobj)
{
var date = dateobj.getDate(), month = dateobj.getMonth()+1, year = dateobj.getFullYear();
var formattddate = (date<10?"0":"")+date+"/"+(month<10?"0":"")+month+"/"+year;
return formattddate;
}
function getWeeksInaMonth()
{
var startdate = new Date(date.getFullYear(), date.getMonth(), 1);
var enddate = new Date(date.getFullYear(), date.getMonth()+1, 0);
var weeks = [];
for(var i=1,n=enddate.getDate();i<n;)
{
startdate.setDate(i);
var arr = [getFormattedDate(startdate)];
i =i+ 6-startdate.getDay();
if(i>n) i=i-(i-n);
startdate.setDate(i);
arr.push(getFormattedDate(startdate));
i++;
weeks.push(arr);
}
return weeks
}
function getCurrentWeek()
{
var today = new Date(), day = today.getDay();
return [getFormattedDate(new Date(today.getFullYear(),today.getMonth(),today.getDate()-day)),
getFormattedDate(new Date(today.getFullYear(),today.getMonth(),today.getDate()+6-day))];
}
function getCurrAndPrevWeeks()
{
var startdate = new Date(date.getFullYear(), date.getMonth(), 1);
var enddate = new Date(date.getFullYear(), date.getMonth()+1, 0);
var today = new Date().getDate();
var weeks = [];
for(var i=1,n=enddate.getDate();i<n;)
{
startdate.setDate(i);
var arr = [getFormattedDate(startdate)];
i =i+ 6-startdate.getDay();
if(i>n) i=i-(i-n);
startdate.setDate(i);
arr.push(getFormattedDate(startdate));
weeks.push(arr);
if(today>=i-6 && today<=i) break;
i++;
}
return weeks;
}

Getting the previous month's first date from current date in JavaScript

Please anyone share the code to find the previous month's first date from current date in JavaScript. For example, if the current date is 25th Jan 2009, I should get 1st Dec 2008 as result.
Straightforward enough, with the date methods:
var x = new Date();
x.setDate(1);
x.setMonth(x.getMonth()-1);
Simplest way would be:
var x = new Date();
x.setDate(0); // 0 will result in the last day of the previous month
x.setDate(1); // 1 will result in the first day of the month
Deals with updating year when moving from January to December
var prevMonth = function(dateObj) {
var tempDateObj = new Date(dateObj);
if(tempDateObj.getMonth) {
tempDateObj.setMonth(tempDateObj.getMonth() - 1);
} else {
tempDateObj.setYear(tempDateObj.getYear() - 1);
tempDateObj.setMonth(12);
}
return tempDateObj
};
var wrapper = document.getElementById('wrapper');
for(var i = 0; i < 12; i++) {
var x = new Date();
var prevDate = prevMonth(x.setMonth(i));
var div = document.createElement('div');
div.textContent =
"start month/year: " + i + "/" + x.getFullYear() +
" --- prev month/year: " + prevDate.getMonth() +
"/" + prevDate.getFullYear() +
" --- locale prev date: " + prevDate.toLocaleDateString();
wrapper.appendChild(div);
}
<div id='wrapper'>
</div>
Important Note: Some of the answers using setMonth() here are wrong:
One liners for use in 2019 (using ES6 syntax; supported by all major browsers and Node):
const date = new Date().toISOString(); // "2019-09-18T13:49:12.775Z"
const [yyyy, mm, dd, h, i, s] = date.split(/T|:|-/);
// previous month's last day
const prev = new Date(new Date().setDate(0)).toISOString();
const [pyyyy, pmm] = prev.split(/T|:|-/);
Note that Array destructuring allows you to skip parts:
const date = new Date().toISOString();
const [, , dd, , i] = date.split(/T|:|-/);
Explanation: The code above gets the ISO date 2019-09-18T13:49:12.775Z and splits it on : or - or T which returns an array [2019, 09, 18, 13, 49, 12] which then gets destructured.
Using setMonth() is wrong:
date = new Date("Dec 31, 2019")
date.setMonth(date.getMonth() - 1);
date; // Dec 1, 2019!
This worked for me
var curDateMonth = new Date();
var prvDateMonth = new Date(curDateMonth.getFullYear(),curDateMonth.getMonth()-1,curDateMonth.getMonth());
console.log(curDateMonth.toLocaleString('en-US', { month: 'long' }) +' vs '+ prvDateMonth.toLocaleString('en-US', { month: 'long' }));
Check this link:
http://blog.dansnetwork.com/2008/09/18/javascript-date-object-adding-and-subtracting-months/
EDIT: I have drummed up an example:
Date.prototype.SubtractMonth = function(numberOfMonths) {
var d = this;
d.setMonth(d.getMonth() - numberOfMonths);
d.setDate(1);
return d;
}
$(document).ready(function() {
var d = new Date();
alert(d.SubtractMonth(1));
});
To get 00:00:00 am of previous month use this:
let d = new Date();
d.setDate(1);
d.setMonth(d.getMonth() - 1);
d.setHours(0,0,0,0);
const lastMonthStart = new Date(d);
Hope this helps!!
// Previous Month Detail
let prevStartDate = new Date(this.date.getFullYear(), this.date.getMonth() - 1, 1);
console.log(prevStartDate);
let preEndDate = new Date(this.date.getFullYear(), this.date.getMonth() - 1 + 1, 0);
console.log(preEndDate);
//Current Month Detail
let cStartDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1);
console.log(cStartDate);
let cEndDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1, 0);
console.log(cEndDate);
//Next Month Detail
let nStartDate = new Date(this.date.getFullYear(), this.date.getMonth() + 1, 1);
console.log(nStartDate);
let nendDate = new Date(this.date.getFullYear(), this.date.getMonth() + 1 + 1, 0);
console.log(nendDate);
//just try this will work fine
let date = new Date();
let month = new Date().getMonth();
let prevMonth = date.setMonth(month - 1)
let formatPrevMonth = new Date(date.setMonth(month - 1));
console.log(formatPrevMonth)
Here, first we assign getMonth() to a variable and incremented it by 1:
var currentMonth = date.getMonth()+1;
var current_date = date.getFullYear()+"/"+currentMonth+"/"+date.getDate();
document.getElementById("p3").innerHTML = "Today,s date:"+current_date;
This can easily be achieved by creating a Date object based on the input date object and changing the date to 1, decrementing the year if it was January and decrementing the month (modulo 12). An important addition to it is to subtract the offset as well.
function getFirstOfPreviousMonth(date) {
let result = new Date(date.getFullYear() - (date.getMonth() ? 0 : 1), (date.getMonth() + 11) % 12, 1);
return new Date(result.getTime() - result.getTimezoneOffset() * 60000);
}
console.log(getFirstOfPreviousMonth(new Date()));
console.log(getFirstOfPreviousMonth(new Date(2009, 0, 25)));

Categories