Moment JS - how to subtract 7 days from current date? - javascript

I would like to subtract 7 days from current date to get formatted date YYYY-MM-DD using moment.js library.
I tried to do by this way:
dateTo = moment(new Date()).format('YYYY-MM-DD');
dateFrom = moment(new Date() - 7).format('YYYY-MM-DD');
console.log(dateFrom);
console.log(dateTo);
But all returned values are same.

May be:
dateTo = moment().format('YYYY-MM-DD');
dateFrom = moment().subtract(7,'d').format('YYYY-MM-DD');
moment#subtract

The date object, when casted, is in milliseconds. so:
dateFrom = moment(Date.now() - 7 * 24 * 3600 * 1000).format('YYYY-MM-DD');

You can use:
moment().subtract(1,'w')
to subtract one week (7 days) from the current date.
NOTE:
1. w for week
2. d for days
3. M for month
4. y for year

for a date picker y use
first_day: moment()
.subtract(5, "day")
.endOf("day")
.toDate(),
last_day: moment()
.endOf("day")
.toDate(),

The question is outdated so does the solution.
Using Moment v2.29 +
You can add or subtract days using following ways
moment().day(-7); // last Sunday (0 - 7)
moment().day(0); // this Sunday (0)
moment().day(7); // next Sunday (0 + 7)
moment().day(10); // next Wednesday (3 + 7)
moment().day(24); // 3 Wednesdays from now (3 + 7 + 7 + 7)
For more please refer the official documentation https://momentjs.com/docs/#/get-set/

Easiest method to get last 7th day
moment().subtract(7, 'days').startOf('day').format('YYYY-MM-DD HH:mm:ss')

Related

generate a specific number of dates from an array of days

if I have an array of : ['Thursday', 'Friday']
and I want to generate 5 dates on the next dates of these days
for example, i want the result is the next Thursday is 14/7/2022, next Friday 15/7/2022
the output should be :
Thursday , Friday , Thursday , Friday , Thursday
=> output ['14/7/2022', '15/7/2022' , '21/7/2022' , '22/7/2022' , '28/7/2022']
If you can use libraries for that, then moment.js will help you a lot.
From that question we can create a solution for your case.
You can use moment.js to get a date from your string, and then using solution from question above get the date of that day of week on next week
This would be doable with two simple function in javascript
The first one would be to know the current date you are in ( & the day )
const d = new Date();
const day = d.getDay();
The getDay() method returns the day of the week (0 to 6) of a date.
Sunday = 0, Monday = 1, ... (See below):
More info here : https://www.w3schools.com/jsref/jsref_getday.asp.
Once you know the date, you would just need to convert your array from
['Thursday', 'Friday']
to [4,5]
Then you need to calculate the offset between the days
let offset = (targetDay - currentDayInNumber) % 7
if (offset < 0) { offset += 7 } // Want to make sure you offset is always positive
An example with tuesday = 2, thursday = 4, or monday = 1
let offset = (4 - 2) % 7 // ( 2 )
let offset = (1 - 2) % 7 // (-1)
offset = -1 + 7 // (6) we will be adding 6 days
Then you can simply loop and add days as you go
var date = new Date();
date.setDate(date.getDate() + days); // For tomorrow + 1 for example
Let me know if that helps, otherwise can provide you with the complete solution, but wanted to guide rather than give solution
-- Edit --
To complete this and to have the occurences, you could have a counter
const counterDays = {
0:0,
1:0,
..,
6:0
}
When going through the loop, everytime you setup a day, you increase the counter for it
This would be become something like this :
date.setDate(date.getDate() + offset + 7 * counterDays[targetDay]);
counterDays[targetDay]++;
I've provided you with the sample code here:
https://onecompiler.com/javascript/3y9sb8dqe
Hope this helps

convert a week number and year to a date object in Javascript

I am very new to web development and I am currently working on a dashboard my data comes from a MySql database. I would like to convert a week number and year to an actual date object in the frontend using javascript. This is my first try, which i stumbled while researching I believe that this function assumes the first day of the week of the current year is Monday(1):
function getDateOfWeek(w, y) {
var d = 1 + (w - 1) * 7;
return new Date(y, 0, d);
}
But the idea that the first day of the week is always Monday is desirable what if otherwise? So upon more research, I modified the code to look like this:
let currentDate = new Date()
let currentYear = currentDate.getFullYear()
let firstOfJan = new Date(currentYear, 0, 1).getDay();
function getDateOfWeek(w, y) {
var d = firstOfJan + (w - firstOfJan) * 7;
return new Date(y, 0, d);
}
Please I am not sure if this solves the problem 100 percent. Is there a downside to the function above? or does it cover it? or I am missing something? Thank you for your time
There are various schemes for calculating week number. ISO 8601 uses Monday before the first Thursday of the year as the start of the first week. So the last few days of a year may be in the first week of the following year, and the first few days may be in the last week of the previous year. There might be 52 or 53 weeks in a year. There are other schemes. Which one do you want to use?
The following converts an ISO week into a Date. It doesn't validate the input, so you'll need to add that.
// Convert week in format yyyyWww (e.g. 2022W05) to Date
function isoWeekToDate(isoWeek) {
let [y, w] = isoWeek.split(/w/i);
// Get date for 4th of January for year
let d = new Date(y, 0, 4);
// Get previous Monday, add 7 days for each week after first
d.setDate(d.getDate() - (d.getDay() || 7) + 1 + (w - 1) * 7);
return d;
}
// Tests
['2010W01',
'2011W01',
'2012W01',
'2013W01',
'2014W01',
'2015W01',
'2016W01',
'2017W01',
'2018W01',
'2019W01',
'2020W01'].forEach(s =>
console.log(isoWeekToDate(s).toDateString())
);

Getting incorrect month difference between 2 dates

I have 2 dates like below :
Todays date = 2021-10-13 11:03:57.560
Old date = 2016-08-07 11:03:57.560
I want month difference from todays date Month - Old date Month = 10 - 8 = 2
Code:
console.log(moment().diff($scope.creationTime, 'months')); // returns 62
Expected: Current month - Old date month
Can anyone please help me with this?
Right now you get 62 because the two dates are 5 years and 2 months apart:
5 * 12 + 2 = 62
An easy way to drop the year difference is to use the remainder operator and do monthDifference % 12 which will give you only the number of months, regardless of the years:
function monthDiff(date1, date2) {
const monthDifference = moment(date1).diff(moment(date2), 'months');
return monthDifference % 12;
}
console.log(monthDiff("2021-10-13 11:03:57.560", "2016-08-07 11:03:57.560"));
console.log(monthDiff("2021-10-07 11:03:57.560", "2016-08-13 11:03:57.560"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Use month() from moment.js to get the months and simple math after that:
const today = moment();
const someday = moment('2011-01-01 00:00Z');
console.log(today.month())
console.log(someday.month())
console.log(Math.abs(today.month()-someday.month()))
You dont need moment to do that you use Date as well
new Date().getMonth - to get your current month
new Date('2016-08-07 11:03:57.560').getMonth() - to get the month of your old date
console.log(new Date().getMonth() - new Date('2016-08-07 11:03:57.560').getMonth())

How to get the 1st date and last date of the current Week as well as Month in the format of 'yyyy-mm-dd' using App Scripts

I am trying to figure out the 1st date and last date of the current week as well as the 1st date and last date of the current month in the format yyyy-mm-dd using Google App scripts. Date() seems to be a difficult object for me, therefore seeking advice. Please consider Saturday is the starting day and Friday is the end day of a week in this parts of the world.
Get first (Saturday) and last (Friday) date of this week
You can use Date.getDay() to get the current day of the week (0=Sunday, 1=Monday, etc.). But there is no method Date.setDay() so we need to do a little math to figure out how many days ago the most recent Saturday was, and use Date.setDate():
// Get the Date for the Saturday on or preceding the current date.
var saturday = new Date(); // Today
var day = date.getDay(); // Day of week (0-6)
var newDay = date.getDate() - ((day + 1) % 7); // The day of the month we want.
saturday.setDate(newDay); // Our date object for Saturday.
(day + 1) % 7 calculates how many days to subtract; for example, if today is Sunday (day=0), we need to go back one day: (0 + 1) % 7 = 1. But if today is Saturday (day=6), we get (6 + 1) % 7 = 0 and we don't subtract any days.
The routine for finding the upcoming Friday is similar, but we add days instead of subtracting:
// Get the Date for the Friday on or after the given date.
var friday = new Date(date); // today
var day = date.getDay();
var diff = date.getDate() + ((5 - day) % 7);
friday.setDate(diff);
Get first and last date of this month
This is simpler using setDate(), since it takes as its parameter the day of the month.
var firstOfMonth = new Date(); // today
firstOfMonth.setDate(1); // Sets the day to the first of the month
To get the last of the month, we go ahead one month, then back to the last day of the previous month (the last of this month):
var lastOfMonth = new Date();
lastOfMonth.setMonth(lastOfMonth.getMonth()+1); // Go ahead one month
lastOfMonth.setDate(0); // Sets to 1 day before the first of the month, i.e. the last of this month.
Convert to format 'yyyy-mm-dd'
Google Apps Script has a built-in method for formatting dates: Utilities.formatDate(date, timezone, format)
date is a Date object, timezone is a string such as those from the TZ database, and format is a string in SimpleDateFormat
For example:
var formattedDate = Utilities.formatDate(friday, 'America/Denver', 'yyyy-MM-dd');
(Note the capital MM for month because mm represents minutes.)
You can use toLocaleString("sv-SE") to convert the date to the desired format yyyy-mm-dd.
Try this:
const today = new Date();
const firstWeekD = today.getDate() - today.getDay()-1;
const lastWeekD = firstWeekD + 6;
const firstdayOfWeek = new Date(today.setDate(firstWeekD)).toLocaleString("sv-SE").slice(0,10);
const lastdayOfWeek = new Date(today.setDate(lastWeekD)).toLocaleString("sv-SE").slice(0,10);
const date = new Date();
const firstDayOfMonth = new Date(date.getFullYear(), date.getMonth(), 1).toLocaleString("sv-SE").slice(0,10);
const lastDayOfMonth = new Date(date.getFullYear(), date.getMonth() + 1, 0).toLocaleString("sv-SE").slice(0,10);
console.log(firstdayOfWeek); // first day of the week - Saturday
console.log(lastdayOfWeek); // last day of the week - Friday
console.log(firstDayOfMonth) // first day of the month
console.log(lastDayOfMonth) // last day of the month

Get the current week using JavaScript without additional libraries ? [SO examples are broken]

I built a calendar control and was adding the week numbers as a final touch, and encountered a problem with every script example I could find on SO and outside of SO (most of which one has copied from the other).
The issue is that when dates fall in partial months, the week calculation seems to mess up and either continue counting when it is the same week in a new month, or it thinks the last full week in a previous month is the same week number as the first full new week in the following month.
Following is a visual demonstration of one of the libraries (they all have their inaccuracies as they generally base their week calculation off a fixed number and build from there) :
You can view the codepen here as the project is rather complex, I have the Date.prototype.getWeek function at the start to play with this easier. Feel free to swap in any code from the samples found here on SO as they all end up funking out on some months.
Some of the calculations used :
Show week number with Javascript?
Date get week number for custom week start day
w3resource.com ISO86901
epoch calendar - getting ISO week
Get week of year in JavaScript like in PHP
When running the most current example (2017) from "Get week of year in JavaScript like in PHP", the week returned right now is 42. When you look on my calendar, the week in October right now is showing as 42 which is correct according to here https://www.epochconverter.com/weeks/2018.
Given the example, there are full weeks sharing the same week number - so I don't see how 42 can even be accurate.
Date.prototype.getWeek = function (dowOffset) {
/*getWeek() was developed by Nick Baicoianu at MeanFreePath: http://www.epoch-calendar.com */
dowOffset = typeof(dowOffset) == 'int' ? dowOffset : 0; //default dowOffset to zero
var newYear = new Date(this.getFullYear(),0,1);
var day = newYear.getDay() - dowOffset; //the day of week the year begins on
day = (day >= 0 ? day : day + 7);
var daynum = Math.floor((this.getTime() - newYear.getTime() -
(this.getTimezoneOffset()-newYear.getTimezoneOffset())*60000)/86400000) + 1;
var weeknum;
//if the year starts before the middle of a week
if(day < 4) {
weeknum = Math.floor((daynum+day-1)/7) + 1;
if(weeknum > 52) {
nYear = new Date(this.getFullYear() + 1,0,1);
nday = nYear.getDay() - dowOffset;
nday = nday >= 0 ? nday : nday + 7;
/*if the next year starts before the middle of
the week, it is week #1 of that year*/
weeknum = nday < 4 ? 1 : 53;
}
}
else {
weeknum = Math.floor((daynum+day-1)/7);
}
return weeknum;
};
Here is some code (also tried this) that is Sunday specific (see near the bottom). I am also pasting the relevant snip here :
/* For a given date, get the ISO week number
*
* Based on information at:
*
* http://www.merlyn.demon.co.uk/weekcalc.htm#WNR
*
* Algorithm is to find nearest thursday, it's year
* is the year of the week number. Then get weeks
* between that date and the first day of that year.
*
* Note that dates in one year can be weeks of previous
* or next year, overlap is up to 3 days.
*
* e.g. 2014/12/29 is Monday in week 1 of 2015
* 2012/1/1 is Sunday in week 52 of 2011
*/
function getWeekNumber(d) {
// Copy date so don't modify original
d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
// Set to nearest Thursday: current date + 4 - current day number
// Make Sunday's day number 7
d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay()||7));
// Get first day of year
var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1));
// Calculate full weeks to nearest Thursday
var weekNo = Math.ceil(( ( (d - yearStart) / 86400000) + 1)/7);
// Return array of year and week number
return [d.getUTCFullYear(), weekNo];
}
The algorithm is to use the week number of the following Saturday. So get the following Saturday, then use it's year for the 1st of Jan. If it's not a Sunday, go to the previous Sunday. Then get the number of weeks from there. It might sound a bit convoluted, but it's only a few lines of code. Most of the following is helpers for playing.
Hopefully the comments are sufficient, getWeekNumber returns an array of [year, weekNumber]. Tested against the Mac OS X Calendar, which seems to use the same week numbering. Please test thoroughly, particularly around daylight saving change over.
/* Get week number in year based on:
* - week starts on Sunday
* - week number and year is that of the next Saturday,
* or current date if it's Saturday
* 1st week of 2011 starts on Sunday 26 December, 2010
* 1st week of 2017 starts on Sunday 1 January, 2017
*
* Calculations use UTC to avoid daylight saving issues.
*
* #param {Date} date - date to get week number of
* #returns {number[]} year and week number
*/
function getWeekNumber(date) {
// Copy date as UTC to avoid DST
var d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
// Shift to the following Saturday to get the year
d.setUTCDate(d.getUTCDate() + 6 - d.getUTCDay());
// Get the first day of the year
var yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
yearStart.setUTCDate(yearStart.getUTCDate() - yearStart.getUTCDay());
// Get difference between yearStart and d in milliseconds
// Reduce to whole weeks
return [d.getUTCFullYear(), (Math.ceil((d - yearStart) / 6.048e8))];
}
// Helper to format dates
function fDate(d) {
var opts = {weekday:'short',month:'short',day:'numeric',year:'numeric'};
return d.toLocaleString(undefined, opts);
}
// Parse yyyy-mm-dd as local
function pDate(s){
var b = (s+'').split(/\D/);
var d = new Date(b[0],b[1]-1,b[2]);
return d.getMonth() == b[1]-1? d : new Date(NaN);
}
// Handle button click
function doButtonClick(){
var d = pDate(document.getElementById('inp0').value);
var span = document.getElementById('weekNumber');
if (isNaN(d)) {
span.textContent = 'Invalid date';
} else {
let [y,w] = getWeekNumber(d);
span.textContent = `${fDate(d)} is in week ${w} of ${y}`;
}
}
Date:<input id="inp0" placeholder="yyyy-mm-dd">
<button type="button" onclick="doButtonClick()">Get week number</button><br>
<span id="weekNumber"></span>

Categories

Resources