Hey i want to get the last 14 days in JavaScript.
I tried following code:
var ourDate = new Date();
for (let index = 0; index < 14; index++) {
var pastDate = ourDate.getDate() - index;
ourDate.setDate(pastDate);
console.log(ourDate.toDateString(), " - ", index);
}
but the console output is following:
Sat Jan 23 2021 - 0
Fri Jan 22 2021 - 1
Wed Jan 20 2021 - 2
Sun Jan 17 2021 - 3
Wed Jan 13 2021 - 4
Fri Jan 08 2021 - 5
Sat Jan 02 2021 - 6
Sat Dec 26 2020 - 7
Fri Dec 18 2020 - 8
Wed Dec 09 2020 - 9
Sun Nov 29 2020 - 10
Wed Nov 18 2020 - 11
Fri Nov 06 2020 - 12
Sat Oct 24 2020 - 13
Which does not make sense.
Could someone help me with this?
I used this code: LINK TO TUTORIAL
I just solved it myself.
I never retested the ourDate so it first removed 0 than 1 than 2 but never reseted.
Just have to create the ourDate in the for loop:
for (let index = 0; index < 14; index++) {
var ourDate = new Date();
var pastDate = ourDate.getDate() - index;
ourDate.setDate(pastDate);
console.log(ourDate.toDateString(), " - ", index);
}
You can try this snippet:
const now = new Date();
const days = Array.from({ length: 14 }, (_, x) => new Date(now - 1000 * 60 * 60 * 24 * x));
for (let day of days) console.log(day.toDateString());
Or a more general solution:
const msInDay = 1000 * 60 * 60 * 24;
const daysAgo = (date, count) => new Date(date - msInDay * count);
const lastDays = (date, count) => Array.from({ length: count }, (_, x) => daysAgo(date, x));
const last14days = lastDays(new Date(), 14);
for (let day of last14days) console.log(day.toDateString());
Hello guys could give me a little help ?
Code here https://jsfiddle.net/pedrowperez/hgb5ufqw/2/`
this is my work.
HTML
<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<p id="demo4"></p>
<p id="demo5"></p>
<p id="demo6"></p>
<p id="demo7"></p>
Javascript
var someDate = new Date();
var Ano_Confirmado = someDate.getFullYear();
var Mes_Confirmado = someDate.getMonth();
var Dia_Confirmado = someDate.getDate();
var Week = 7;
var Day = 1;
var someDateD = new Date(Ano_Confirmado, Mes_Confirmado, (Dia_Confirmado) - Week);
document.getElementById('demo1').innerHTML = (someDateD);
someDateD.setDate(someDateD.getDate() + Day);
document.getElementById('demo2').innerHTML = (someDateD);
someDateD.setDate(someDateD.getDate() + Day);
document.getElementById('demo3').innerHTML = (someDateD);
someDateD.setDate(someDateD.getDate() + Day);
document.getElementById('demo4').innerHTML = (someDateD);
someDateD.setDate(someDateD.getDate() + Day);
document.getElementById('demo5').innerHTML = (someDateD);
someDateD.setDate(someDateD.getDate() + Day);
document.getElementById('demo6').innerHTML = (someDateD);
someDateD.setDate(someDateD.getDate() + Day);
document.getElementById('demo7').innerHTML = (someDateD);
Result
Tue Jan 26 2016 00:00:00 GMT-0200 (E. South America Daylight Time)
Wed Jan 27 2016 00:00:00 GMT-0200 (E. South America Daylight Time)
Thu Jan 28 2016 00:00:00 GMT-0200 (E. South America Daylight Time)
Fri Jan 29 2016 00:00:00 GMT-0200 (E. South America Daylight Time)
Sat Jan 30 2016 00:00:00 GMT-0200 (E. South America Daylight Time)
Sun Jan 31 2016 00:00:00 GMT-0200 (E. South America Daylight Time)
Mon Feb 01 2016 00:00:00 GMT-0200 (E. South America Daylight Time)
Tue Feb 02 2016 00:00:00 GMT-0200 (E. South America Daylight Time)
Wed Feb 03 2016 00:00:00 GMT-0200 (E. South America Daylight Time)
I need to change the date format : Wed Mar 23 2016 15:19:36 GMT-0300 (E. South America Standard Time)
for this format: DD/MM
But I can not find anything Referring dates will list in javascript;
There are two options that come to mind:
Use the Date methods, though this is relatively limiting
Use a library like Moment.js.
Using Date methods
someDate.getDay() + '/' + (someDate.getMonth() + 1);
The (someDate.getMonth() + 1) is required because getMonth() returns the zero-indexed month. Meaning January is 0, February is 1 and so on.
Using Moment.js
Look into a library like . Using Moment you can format dates in endless ways:
moment(someDateD).format('DD/MM');
Here's your updated JSFiddle.
You can create your own function that handles it if you don't need any other complex manipulations with dates.
function formateDate(date) {
function addZero_(num) {
return num < 10 ? ('0' + num) : num);
}
var day = date.getDate();
var month = date.getMonth() + 1;
return addZero_(day) + '/' + addZero_(month);
}
document.getElementById('demo3').innerHTML = formateDate(someDateD);
Also use for to set date values in dom.
I am trying to calculate number of weeks in a month using moment js. But I am getting wrong results for some months like May 2015 and August 2015.
I am using this code.
var start = moment().startOf('month').format('DD');
var end = moment().endOf('month').format('DD');
var weeks = (end-start+1)/7;
weeks = Math.ceil(weeks);
Is there any prebuilt method in moment JS for getting number of weeks.
I have created this gist that finds all the weeks in a given month and year. By calculated the length of calendar, you will know the number of weeks.
https://gist.github.com/guillaumepiot/095b5e02b4ca22680a50
# year and month are variables
year = 2015
month = 7 # August (0 indexed)
startDate = moment([year, month])
# Get the first and last day of the month
firstDay = moment(startDate).startOf('month')
endDay = moment(startDate).endOf('month')
# Create a range for the month we can iterate through
monthRange = moment.range(firstDay, endDay)
# Get all the weeks during the current month
weeks = []
monthRange.by('days', (moment)->
if moment.week() not in weeks
weeks.push(moment.week())
)
# Create a range for each week
calendar = []
for week in weeks
# Create a range for that week between 1st and 7th day
firstWeekDay = moment().week(week).day(1)
lastWeekDay = moment().week(week).day(7)
weekRange = moment.range(firstWeekDay, lastWeekDay)
# Add to the calendar
calendar.push(weekRange)
console.log calendar
Can be easily done using raw javascript:
function getNumWeeksForMonth(year,month){
date = new Date(year,month-1,1);
day = date.getDay();
numDaysInMonth = new Date(year, month, 0).getDate();
return Math.ceil((numDaysInMonth + day) / 7);
}
You get the day index of the first day, add it to the number of days to compensate for the number of days lost in the first week, divide by 7 and use ceil to add 1 for the simplest overflow in the next week
It display the list of weeks in a month with 'moment.js'.
It has been written in typescript with angular 6+.
Install moment with 'npm i moment'
Inside the ts file.
weeks_in_month() {
let year = 2019; // change year
let month = 4; // change month here
let startDate = moment([year, month - 1])
let endDate = moment(startDate).endOf('month');
var dates = [];
var weeks = [];
var per_week = [];
var difference = endDate.diff(startDate, 'days');
per_week.push(startDate.toDate())
let index = 0;
let last_week = false;
while (startDate.add(1, 'days').diff(endDate) < 0) {
if (startDate.day() != 0) {
per_week.push(startDate.toDate())
}
else {
if ((startDate.clone().add(7, 'days').month() == (month - 1))) {
weeks.push(per_week)
per_week = []
per_week.push(startDate.toDate())
}
else if (Math.abs(index - difference) > 0) {
if (!last_week) {
weeks.push(per_week);
per_week = [];
}
last_week = true;
per_week.push(startDate.toDate());
}
}
index += 1;
if ((last_week == true && Math.abs(index - difference) == 0) ||
(Math.abs(index - difference) == 0 && per_week.length == 1)) {
weeks.push(per_week)
}
dates.push(startDate.clone().toDate());
}
console.log(weeks);
}
Result:
Array of date moments.
[Array(6), Array(7), Array(7), Array(7), Array(3)]
0: (6) [Mon Apr 01 2019 00:00:00 GMT+0530 (India Standard Time),
Tue Apr 02 2019 00:00:00 GMT+0530 (India Standard Time),
Wed Apr 03 2019 00:00:00 GMT+0530 (India Standard Time),
Thu Apr 04 2019 00:00:00 GMT+0530 (India Standard Time),
Fri Apr 05 2019 00:00:00 GMT+0530 (India Standard Time),
Sat Apr 06 2019 00:00:00 GMT+0530 (India Standard Time)]
1: (7) [Sun Apr 07 2019 00:00:00 GMT+0530 (India Standard Time),
Mon Apr 08 2019 00:00:00 GMT+0530 (India Standard Time),
Tue Apr 09 2019 00:00:00 GMT+0530 (India Standard Time),
Wed Apr 10 2019 00:00:00 GMT+0530 (India Standard Time),
Thu Apr 11 2019 00:00:00 GMT+0530 (India Standard Time),
Fri Apr 12 2019 00:00:00 GMT+0530 (India Standard Time),
Sat Apr 13 2019 00:00:00 GMT+0530 (India Standard Time)]
2: (7) [Sun Apr 14 2019 00:00:00 GMT+0530 (India Standard Time),
Mon Apr 15 2019 00:00:00 GMT+0530 (India Standard Time),
Tue Apr 16 2019 00:00:00 GMT+0530 (India Standard Time),
Wed Apr 17 2019 00:00:00 GMT+0530 (India Standard Time),
Thu Apr 18 2019 00:00:00 GMT+0530 (India Standard Time),
Fri Apr 19 2019 00:00:00 GMT+0530 (India Standard Time),
Sat Apr 20 2019 00:00:00 GMT+0530 (India Standard Time)]
3: (7) [Sun Apr 21 2019 00:00:00 GMT+0530 (India Standard Time),
Mon Apr 22 2019 00:00:00 GMT+0530 (India Standard Time),
Tue Apr 23 2019 00:00:00 GMT+0530 (India Standard Time),
Wed Apr 24 2019 00:00:00 GMT+0530 (India Standard Time),
Thu Apr 25 2019 00:00:00 GMT+0530 (India Standard Time),
Fri Apr 26 2019 00:00:00 GMT+0530 (India Standard Time),
Sat Apr 27 2019 00:00:00 GMT+0530 (India Standard Time)]
4: (3) [Sun Apr 28 2019 00:00:00 GMT+0530 (India Standard Time),
Mon Apr 29 2019 00:00:00 GMT+0530 (India Standard Time),
Tue Apr 30 2019 00:00:00 GMT+0530 (India Standard Time)]
EDIT:
NEW and hopefully very correct implementation:
function calcWeeksInMonth(date: Moment) {
const dateFirst = moment(date).date(1);
const dateLast = moment(date).date(date.daysInMonth());
const startWeek = dateFirst.isoWeek();
const endWeek = dateLast.isoWeek();
if (endWeek < startWeek) {
// Yearly overlaps, month is either DEC or JAN
if (dateFirst.month() === 0) {
// January
return endWeek + 1;
} else {
// December
if (dateLast.isoWeekday() === 7) {
// Sunday is last day of year
return endWeek - startWeek + 1;
} else {
// Sunday is NOT last day of year
return dateFirst.isoWeeksInYear() - startWeek + 1;
}
}
} else {
return endWeek - startWeek + 1;
}
}
Outputs the following values for the following dates:
calcWeeksInMonth(moment("2016-12-01")); // 5
calcWeeksInMonth(moment("2017-01-01")); // 6
calcWeeksInMonth(moment("2017-02-01")); // 5
calcWeeksInMonth(moment("2017-03-01")); // 5
calcWeeksInMonth(moment("2017-04-01")); // 5
calcWeeksInMonth(moment("2017-05-01")); // 5
calcWeeksInMonth(moment("2017-06-01")); // 5
calcWeeksInMonth(moment("2017-07-01")); // 6
calcWeeksInMonth(moment("2017-08-01")); // 5
calcWeeksInMonth(moment("2017-09-01")); // 5
calcWeeksInMonth(moment("2017-10-01")); // 6
calcWeeksInMonth(moment("2017-11-01")); // 5
calcWeeksInMonth(moment("2017-12-01")); // 5
calcWeeksInMonth(moment("2018-01-01")); // 5
OLD and very incorrect implementation:
calcWeeksInMonth(date) {
const dateFirst = moment(date).date(1)
const dateLast = moment(date).date(date.daysInMonth())
const startWeek = dateFirst.week()
const endWeek = dateLast.week()
if (endWeek < startWeek) {
return dateFirst.weeksInYear() - startWeek + 1 + endWeek
} else {
return endWeek - startWeek + 1
}
}
This seems to output correct results, feedback welcome if there is something I missed!
function getWeekNums(momentObj) {
var clonedMoment = moment(momentObj), first, last;
// get week number for first day of month
first = clonedMoment.startOf('month').week();
// get week number for last day of month
last = clonedMoment.endOf('month').week();
// In case last week is in next year
if( first > last) {
last = first + last;
}
return last - first + 1;
}
javaScript version here
var year = 2021
var month = 6
var startDate = moment([year, month])
//Get the first and last day of the month
var firstDay = moment(startDate).startOf('month')
var endDay = moment(startDate).endOf('month')
//Create a range for the month we can iterate through
var monthRange = moment.range(firstDay, endDay)
//Get all the weeks during the current month
var weeks = []
var indexOf = [].indexOf;
monthRange.by('days', function (moment) {
var ref;
if (ref = moment.week(), indexOf.call(weeks, ref) < 0) {
return weeks.push(moment.week());
}
});
var calendar, firstWeekDay, i, lastWeekDay, len, week, weekRange;
calendar = [];
for (i = 0, len = weeks.length; i < len; i++) {
week = weeks[i];
// Create a range for that week between 1st and 7th day
firstWeekDay = moment().week(week).day(0);
lastWeekDay = moment().week(week).day(6);
weekRange = moment.range(firstWeekDay, lastWeekDay);
// Add to the calendar
calendar.push(weekRange);
}
This is the best way out , works well
moment.relativeTime.dd = function (number) {
// round to the closest number of weeks
var weeks = Math.round(number / 7);
if (number < 7) {
// if less than a week, use days
return number + " days";
} else {
// pluralize weeks
return weeks + " week" + (weeks === 1 ? "" : "s");
}
}
Source:How to get duration in weeks with Moment.js?
I have not seen a solution that works in all circumstances. I tried all of these but they all are flawed in one way or another. Ditto with several moment.js github threads. This was my crack at it:
getNumberOfWeeksInMonth = (momentDate) => {
const monthStartWeekNumber = momentDate.startOf('month').week();
const distinctWeeks = {
[monthStartWeekNumber]: true
};
let startOfMonth = momentDate.clone().startOf('month');
let endOfMonth = momentDate.clone().endOf('month');
// this is an 'inclusive' range -> iterates through all days of a month
for (let day = startOfMonth.clone(); !day.isAfter(endOfMonth); day.add(1, 'days')) {
distinctWeeks[day.week()] = true
}
return Object.keys(distinctWeeks).length;
}
function weeksInMonth(date = null){
let firstDay = moment(date).startOf('month');
let endDay = moment(date).endOf('month');
let weeks = [];
for (let i = firstDay.week(); i <= endDay.week(); i++){
weeks.push(i)
}
return weeks;
}
Here is a simple way of doing it (based on a solution posted above):
const calcWeeksInMonth = (momentDate) => {
const dateFirst = moment(momentDate).date(1)
const dateLast = moment(momentDate).date(momentDate.daysInMonth())
const startWeek = dateFirst.isoWeek()
const endWeek = dateLast.isoWeek()
if (endWeek < startWeek) {
// cater to end of year (dec/jan)
return dateFirst.weeksInYear() - startWeek + 1 + endWeek
} else {
return endWeek - startWeek + 1
}
}
As far as I can tell, it works correctly for any date thrown at it, but feedback is always welcome!
Throwing this into the mix
import moment from "moment";
export const calcWeeksInMonth = date => {
let weekMonthEnds = moment(date)
.date(moment(date).daysInMonth())
.week();
let weekMonthStarts = moment(date)
.date(1)
.week();
return weekMonthEnds < weekMonthStarts
? moment(date).isoWeeksInYear() - weekMonthStarts + 1
: weekMonthEnds - weekMonthStarts + 1;
};
var month = moment().month();
var startOfMonth = month.startOf("month");
var endOfMonth = month.endOf("month");
var startWeekNumber = startOfMonth.isoWeek();
var endWeekNumber = endOfMonth.isoWeek();
var numberOfWeeks = (endWeekNumber - startWeekNumber + 1);
console.log(numberOfWeeks);
If you have selectedDate value that is give you opportunity to detect which month is active now:
private calculateNumberOfWeeks(): number {
const end = moment(this.selectedDate).endOf('month');
const startDay = moment(this.selectedDate)
.startOf('month')
.day();
const endDay = end.day();
const endDate = end.date();
return (startDay - 1 + endDate + (endDay === 0 ? 0 : 7 - endDay)) / 7;
}
/UPDATE/
Solution below did not take in consideration jump to the new year.
Here is the improved solution.
const getNumberOfWeeksInAMonth = (currentMoment: moment.Moment) => {
const currentMomentCopy = cloneDeep(currentMoment)
const startOfMonth = currentMomentCopy.startOf('month')
const startOfISOWeek = startOfMonth.startOf('isoWeek')
let numberOfWeeks = 0;
do {
numberOfWeeks++
MomentManager.addWeek(startOfISOWeek)
} while (currentMoment.month() === startOfISOWeek.month())
return numberOfWeeks;
}
I have found another solution with momentjs.
const getNumberOfWeeksInMonth = (moment: moment.Moment) => {
const startWeek = moment.startOf('month').isoWeek()
const endWeek = moment.endOf('month').isoWeek()
return endWeek - startWeek + 1
}
js:
service.search = function (goDate, returnDate) {
var outwardInterval = {};
outwardInterval.start = moment(goDate, 'YYYY-MM-DD').subtract(3, 'day');
outwardInterval.end = moment(goDate, 'YYYY-MM-DD').add(3, 'day');
matrice.outwardDates = buildDateArray(outwardInterval);
}
var buildDateArray = function (interval) {
var array = [];
var currentDate = interval.start;
do {
array.push(currentDate);
currentDate.add(1, 'day');
} while (!currentDate.isAfter(interval.end));
return array;
};
My output:
Why in my array i have the same value ..?
Update:
JSFIDDLE
Extending My comment:
function GetDates(startDate, daysToAdd) {
var aryDates = [];
for(var i = 0; i <= daysToAdd; i++) {
var currentDate = new Date();
currentDate.setDate(startDate.getDate() + i);
aryDates.push(DayAsString(currentDate.getDay()) + ", " + currentDate.getDate() + " " + MonthAsString(currentDate.getMonth()) + " " + currentDate.getFullYear());
}
return aryDates;
}
function MonthAsString(monthIndex) {
var d=new Date();
var month=new Array();
month[0]="Jan";
month[1]="Feb";
month[2]="March";
month[3]="April";
month[4]="May";
month[5]="June";
month[6]="July";
month[7]="Aug";
month[8]="Sep";
month[9]="Oct";
month[10]="Nov";
month[11]="Dec";
return month[monthIndex];
}
function DayAsString(dayIndex) {
var weekdays = new Array(7);
weekdays[0] = "Sun";
weekdays[1] = "Mon";
weekdays[2] = "Tue";
weekdays[3] = "Wed";
weekdays[4] = "Thu";
weekdays[5] = "Fri";
weekdays[6] = "Sat";
return weekdays[dayIndex];
}
var startDate = new Date();
var aryDates = GetDates(startDate, 7);
console.log(aryDates);
Fiddle: http://jsfiddle.net/u93g87qc/2/
Actually you're not getting the same date for every value in the array. You're fighting moment.js here. If you slightly modify your code to execute the toDate method of the moment you'll see that it's working just fine:
var matrice = { };
var service = { };
service.search = function (goDate, returnDate) {
var outwardInterval = {};
outwardInterval.start = moment(goDate, 'YYYY-MM-DD').subtract(3, 'day');
outwardInterval.end = moment(goDate, 'YYYY-MM-DD').add(3, 'day');
matrice.outwardDates = buildDateArray(outwardInterval);
}
var buildDateArray = function (interval) {
console.clear();
console.log('Start: ', interval.start.toDate());
console.log('End: ', interval.end.toDate());
var array = [];
var currentDate = interval.start;
console.log('Initial date: ', currentDate.toDate());
do {
array.push(currentDate.toDate());
currentDate.add(1, 'days');
console.log('Current date: ', currentDate.toDate());
} while (!currentDate.isAfter(interval.end));
return array;
};
service.search('2014-12-25');
Output:
Start: Mon Dec 22 2014 00:00:00 GMT-0700 (Mountain Standard Time)
End: Sun Dec 28 2014 00:00:00 GMT-0700 (Mountain Standard Time)
Initial date: Mon Dec 22 2014 00:00:00 GMT-0700 (Mountain Standard Time)
Current date: Tue Dec 23 2014 00:00:00 GMT-0700 (Mountain Standard Time)
Current date: Wed Dec 24 2014 00:00:00 GMT-0700 (Mountain Standard Time)
Current date: Thu Dec 25 2014 00:00:00 GMT-0700 (Mountain Standard Time)
Current date: Fri Dec 26 2014 00:00:00 GMT-0700 (Mountain Standard Time)
Current date: Sat Dec 27 2014 00:00:00 GMT-0700 (Mountain Standard Time)
Current date: Sun Dec 28 2014 00:00:00 GMT-0700 (Mountain Standard Time)
Current date: Mon Dec 29 2014 00:00:00 GMT-0700 (Mountain Standard Time)
I am getting the current date in javascript and then I convert it to the current month. Based on the current month (9 now), I want to print the month calendar for the last 3 years backwards. So, if we have September 2013, the following has to be printed:
08 09 10 11 12 2010
01 02 03 04 05 06 07 08 09 10 11 12 2011
01 02 03 04 05 06 07 08 09 10 11 12 2012
01 02 03 04 05 06 07 08 2013
I have a general idea how to print the first line, but I'm struggling how to print the rest of the calendar. Here is my code for the first line (2013):
function printCalendarRows(){
var d = new Date();
var n = (d.getMonth()) + 1;
var twelve = 12;
for(var i = n; i <= 12; i++){
for(var j = 12; j >= n; j--){
console.log(i);
console.log(j);
}
}
}
Any recommendations? Thanks
function calRows() {
var date,
now = new Date(),
str = "";
for (var i = -37;i++;) {
date = new Date(now.getFullYear(), now.getMonth() + i - 1, 1)
month = ("0" + (date.getMonth() + 1)).slice(-2);
str += month + " " + (+month % 12 == 0 ? date.getFullYear() + "\n" : "")
}
return str + date.getFullYear();
}
console.log (calRows()) /*
08 09 10 11 12 2010
01 02 03 04 05 06 07 08 09 10 11 12 2011
01 02 03 04 05 06 07 08 09 10 11 12 2012
01 02 03 04 05 06 07 08 2013 */
Heres a Fiddle
Or if you prefer, the same without assigning a new Date object in the loop.
function calRows() {
var date,
now = new Date(),
first = new Date(now.getFullYear(), now.getMonth() -37, 1),
monthYear = [first.getMonth(),first.getFullYear()]
str = "";
for (var i = -37;i++;) {
month = ("0" + (++monthYear[0])).slice(-2);
str += month + " " + (+month % 12 == 0 ? (monthYear[0]=0,monthYear[1]++) + "\n" : "")
}
return str + monthYear[1]
}
Check if this is what you want
function printCalendarRows(){
var d = new Date();
var o = new Date();
o.setMonth( (d.getMonth()) - 36); //or o.setFullYear( (d.getFullYear()) - 3);
var currnt;
while (o < d)
{
currnt = o.getMonth();
console.log(currnt);
if (currnt == 11)
{
console.log(o.getFullYear());
}
o.setMonth(currnt+1);
}
if (d.getMonth() != 11)
{
console.log(d.getFullYear());
}
alert("Date:"+ d + "Month:" + d.getMonth());
}
I would use momentjs:
function printCalendarRows(){
var d = moment().subtract('months', 37);
var y = d.format("YYYY");
var n = moment().format("MM/YYYY");
var log = "";
while(d.format("MM/YYYY") != n) {
if (d.format("YYYY") != y) {
console.log(log + y + "\r\n");
y = d.format("YYYY");
log = "";
}
log += d.format("MM") + " ";
d = d.add("months", 1);
}
console.log(log + d.format("YYYY"));
}
printCalendarRows();
working DEMO