Getting incorrect month difference between 2 dates - javascript

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())

Related

Number of days in the months corresponding to selected dates

I need to find the number of days as days from months chosen between two dates. For example, if I choose date1 as January 1,2021 and date2 as March 1, 2021, then I need to get the total number of days in January, February and March.
Output=
Number of days in january + Number of days in february + Number of days in march = 31+28+31
What I tried:
const getDiff=(selectedDate1,selectedDate2)=>{
console.log('Date check',moment(selectedDate1).daysInMonth(),moment(new Date()).daysInMonth())
if(moment(selectedDate1).daysInMonth() - moment(selectedDate2).daysInMonth() ===0){
return Number(moment(selectedDate1).daysInMonth())
}else{
return Number(moment(selectedDate1).daysInMonth())+Number(moment(selectedDate2).daysInMonth())
}
}
But with this code, i am getting only the sum of days of the selected dates, ie. only Number of days in January + Number of days in March
Using moment.js, you just get the difference between start of the start month and end of the end month in days plus 1 (because the end of month won't include the last day and adding 1 is simpler than going to the start of the following month), e.g.
function wholeMonthDays(d1, d2) {
let diff = moment(d2).endOf('month').diff(moment(d1).startOf('month'),'days') + 1;
return diff;
}
let start = new Date(2021,0,21);
let end = new Date(2021,2,11);
console.log(wholeMonthDays(start, end)); // 90
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Alternatively you can go to the start of the month after end to get the difference:
function wholeMonthDays(d1, d2) {
let start = moment(d1).startOf('month');
let end = moment(d2).startOf('month').add(1, 'month');
let diff = end.diff(start, 'days');
return diff;
}
let start = new Date(2021, 0, 21);
let end = new Date(2021, 2, 11);
console.log(wholeMonthDays(start, end)); // 90
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
I've set the dates to during the month to show that it adds the "days in months" rather than just the difference between the two dates.
If you actually want an array of the total days in each month, just set the start to the end of the month, get the date, add one month, set to the end of the month, etc. until you've gone past the end month.
A couple of things:
Remember that Months in Java and JavaScript are (moronically) 0-based. So month 1 is February
To get the number of days in a month you can use a Date object and go to the first of the next month, then substract 1 day, then call getDay.
The time between two dates in milliseconds is
var d1 = ...;
var d2 = ...;
var duration = Math.abs(d2.getTime() - d1.getTime());
You can then divide duration by milliseconds (1000), seconds (60), minutes (60) etc to get the timespan in the unites you'd
The simplest way would be:
// 'lo' and 'hi' could be of type Date or numbers coming from Date.getTime()
const daysBetween = (lo, hi) => {
const oneDayInMilliseconds
= 1000 // one sec has 1000 millis
* 3600 // one hour has 3600 seconds
* 24; // one day has 24 hours
return (hi - lo) / oneDayInMilliseconds;
}

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

Javascript Date object not showing correct month

I'm trying to use the Javascript Date object to calculate a date in the future (3 months from today). I am however getting unexpected results, specifically, when adding 3 months, the output date is 2025 (for time travelers, it's 2018 this year)!
Doing a simple console.log returns some unexpected results as below:
var d = new Date();
console.log("Locale Time:"+ d.toLocaleDateString());
console.log("Month: "+d.getMonth());
d.setMonth(d.getMonth() + 3);
console.log("3 months from now: "+d.toLocaleDateString());
Returns:
// Note todays real date is 9 October 2018
Locale Time:10/9/2018 // This is correct
app.min.js:1 Month: 9 // No, the month is 10 (October)
app.min.js:1 3 months from now: 11/9/2025 // What?
What am I doing wrong?
The argument monthIndex is 0-based. This means that January = 0 and December = 11.
so your code can be like this :
var d = new Date();
console.log("Locale Time:"+ d.toLocaleDateString());
console.log("Month: "+d.getMonth());
d.setMonth(d.getMonth() + 4);
console.log("3 months from now: "+d.toLocaleDateString());
Output will be
> "Locale Time:10/9/2018"
> "Month: 9" (October = 9 as monthIndex starts from 0)
> "3 months from now: 2/9/2019"

Momentjs - Week Numbers When April Is Week One

Using this function in momentjs I can find the week number of the year:
var dt = new Date();
var weekNumber = moment(dt).week();
Can anyone tell me how to set the first week in April as week one, and therefore for week 52 to be the last week in March.
In the documentation I can only see how to adjust the first day of the year (ie Sunday or Monday). I need to do both. Saturday will actually be day one.
Help much appreciated.
You will have to add a custom function,
Sample
function getCustomWeekNumber(weekNo) {
var baseWeek = moment("01/04/", "DD/MM/").week() - 1; // 13
var lastWeek = moment("31/12/", "DD/MM/").week() //53;
return weekNo > baseWeek ? weekNo - baseWeek : (lastWeek - baseWeek) + weekNo;
}
var d = moment().week();
console.log(getCustomWeekNumber(d))
d = moment("01/04/2016", "DD/MM/YYYY").week();
console.log(getCustomWeekNumber(d))
d = moment("24/03/2016", "DD/MM/YYYY").week();
console.log(getCustomWeekNumber(d))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.0/moment.min.js"></script>

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

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')

Categories

Resources