Using moment to calculate the number of days between 2 dates - javascript

I'm trying to work out the number of days between 2 dates in Javascript with the following code.
console.log(self.StartDate());
var start = moment(self.StartDate(), "YYYY-MM-DD");
console.log(start);
console.log(self.EndDate());
var end = moment(self.EndDate(), "YYYY-MM-DD");
console.log(end);
var duration = moment.duration(start.diff(end));
console.log(duration);
//no of days between start and end
console.log(duration.asDays());
console output:
Thu Jun 20 2019 01:00:00 GMT+0100 (British Summer Time)
n {_isAMomentObject: true, _i: Thu Jun 20 2019 01:00:00 GMT+0100 (British Summer Time), _f: "YYYY-MM-DD", _isUTC: false, _pf: {…}, …}_d: Wed Aug 19 0020 00:00:00 GMT-0001 (British Summer Time) {}_f: "YYYY-MM-DD"_i: Thu Jun 20 2019 01:00:00 GMT+0100 (British Summer Time) {}_isAMomentObject: true_isUTC: false_locale: r {_ordinalParse: /\d{1,2}(th|st|nd|rd)/, ordinal: ƒ, _abbr: "en", _ordinalParseLenient: /\d{1,2}(th|st|nd|rd)|\d{1,2}/}_pf: {empty: false, unusedTokens: Array(0), unusedInput: Array(3), overflow: 1, charsLeftOver: 49, …}__proto__: Object
Mon Jun 24 2019 15:10:41 GMT+0100 (British Summer Time)
n {_isAMomentObject: true, _i: Mon Jun 24 2019 15:10:41 GMT+0100 (British Summer Time), _f: "YYYY-MM-DD", _isUTC: false, _pf: {…}, …}
Ea {_milliseconds: -126230400000, _days: 0, _months: 0, _data: {…}, _locale: r}
-1461
self.StartDate() is 20/06/2019 and self.EndDate() is 24/06/2019 so I'm exciting the alert to display 4 however it displays -1461.
Why is this the case?

The problem is that your dates are not formatted the way you tell moment.js they are. 20/06/2019 is DD/MM/YYYY and not YYYY-MM-DD. As per the documentation, non-numeric characters are ignored so 20/06/2019 would be parsed as 2006-20-19. Since such a date does not exist, Moment.js tries to guess what you actually meant and it comes up with 2020-06-19:
var start = moment("20/06/2019", "YYYY-MM-DD");
console.log(start);
<script src="https://cdn.jsdelivr.net/momentjs/2.14.1/moment-with-locales.min.js"></script>
Same thing happens with the end date.
You need to either change the format you tell to Moment.js or fix the start and end dates to use the format you specified, in both cases, you'd get the correct result:
var self = {
StartDate: () => "20/06/2019",
EndDate: () => "24/06/2019"
}
var start = moment(self.StartDate(), "DD/MM/YYYY"); //using the correct format
var end = moment(self.EndDate(), "DD/MM/YYYY");
var duration = moment.duration(start.diff(end));
console.log(duration.asDays());
<script src="https://cdn.jsdelivr.net/momentjs/2.14.1/moment-with-locales.min.js"></script>
var self = {
StartDate: () => "2019-06-20", //using dates in the correct format
EndDate: () => "2019-06-24"
}
var start = moment(self.StartDate(), "YYYY-MM-DD");
var end = moment(self.EndDate(), "YYYY-MM-DD");
var duration = moment.duration(start.diff(end));
console.log(duration.asDays());
<script src="https://cdn.jsdelivr.net/momentjs/2.14.1/moment-with-locales.min.js"></script>

Your code should work perfectly fine. You should only swap start and end at the defference calculation to get positive values.
var startDate = moment("2019-06-20", "YYYY-MM-DD");
var endDate = moment("2019-06-24", "YYYY-MM-DD");
var duration = moment.duration(startDate.diff(endDate));
//no of days between start and end
console.log(duration.asDays());
var duration = moment.duration(endDate.diff(startDate));
console.log(duration.asDays());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
If you are only interested in the difference calculated in days, this code will be shorter:
var startDate = moment("2019-06-20", "YYYY-MM-DD");
var endDate = moment("2019-06-24", "YYYY-MM-DD");
var diff = startDate.diff(endDate, 'days');
console.log(diff);
var diff = endDate.diff(startDate, 'days');
console.log(diff);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
There has to be some issue with the dates themselves.
And in fact, it's the way you parse the date strings
// This is parsed as the 19th day of 6th month in year 2020
var startDate = moment("20/06/2019", "YYYY-MM-DD");
// This is parsed as the 19th day of 6th month in year 2024
var endDate = moment("24/06/2019", "YYYY-MM-DD");
var diff = endDate.diff(startDate, 'days');
console.log({"start": startDate, "end": endDate, "diff": diff});
// You either need to change the date strings or the format strings
var startDate = moment("20/06/2019", "DD/MM/YYYY");
var endDate = moment("24/06/2019", "DD/MM/YYYY");
var diff = endDate.diff(startDate, 'days');
console.log({"start": startDate, "end": endDate, "diff": diff});
// You either need to change the date strings or the format strings
var startDate = moment("2019-06-20", "YYYY-MM-DD");
var endDate = moment("2019-06-24", "YYYY-MM-DD");
var diff = endDate.diff(startDate, 'days');
console.log({"start": startDate, "end": endDate, "diff": diff});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>

Your date is invalid, you specified a start date of "20/06/2019" which is a template of "DD/MM/YYYY", but told moment to use the template of "YYYY-MM-DD".
You simply need to replace the template that you pass to moment, and here is a bit cleaner way to do it:
const DEFAULT_DATE_TEMPLATE = "DD/MM/YYYY";
const getDaysBetweenDates = (date1, date2, dateTemplate = DEFAULT_DATE_TEMPLATE) => {
const start = moment(date1, dateTemplate);
const end = moment(date2, dateTemplate);
const duration = moment.duration(start.diff(end));
const daysDiff = duration.asDays();
// for your example you will get -4, abs will make it into 4 for you
return Math.abs(daysDiff);
}
const myDiff = getDaysBetweenDates('20/06/2019', '24/06/2019');
console.log(myDiff); // 4
// or if you rather keep your other template
const myDiff2 = getDaysBetweenDates('2019-06-20', '2019-06-24', 'YYYY-MM-DD');
console.log(myDiff2); // 4

Related

how to get all weekdays from a date range and duration

So i have an initialDate, a travelTime and a endDate,
we also have booleans representing the weekdays
lets say we whave the following:
initialDate = 06 Jun 2021
travelTime = 13:00 to 18:00
mon = true, tue = false, wed = true, thu: false, fri = false
endDate = initialDate + 1 month
i need to get all mondays and wednesday dates between initialDate and endDate
In this code bellow, using momentjs, I create two array, one for Mondays and one for Wednesdays formatted like you wrote the date in your question.
const dateFormatTemplate = 'DD MMM YYYY';
const initialDate = moment('06 Jun 2021', dateFormatTemplate);
const endDate = moment(initialDate).add(1, 'month');
const MONDAY = 1; // moment().day() return a value from 0 to 6(Sunday-to-Saturday)
const WEDNESDAY = 3;
const mondayArray = [];
const wednesdayArray = [];
while (initialDate.isSameOrBefore(endDate)) {
if (initialDate.day() === MONDAY) mondayArray.push(initialDate.format(dateFormatTemplate));
else if (initialDate.day() === WEDNESDAY) wednesdayArray.push(initialDate.format(dateFormatTemplate));
initialDate.add(1, 'day');
}
console.log('ALL MONDAY', mondayArray)
console.log('ALL WEDNESDAY', wednesdayArray);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

adding days to historical dates in app script [duplicate]

This question already has answers here:
How to add days to Date?
(56 answers)
Closed 2 years ago.
I am trying to pull some historical data, which has a variety of time stamps. I want the use to a user selected date, and then pull all days + some additional days.
Date1 is
var Date1 = "Thu Oct 22 00:00:00 GMT-04:00 2020"
var startDate = new Date(Date1)
var Enddate = new Date();
Enddate.setDate(startDate + 10);
This doesn't work. I cant seem to figure out how to add the "10 days" to the Date1 variable.
You need the getDate function of the Date object, and you'll need to pass the correct value when instantiating the new Date.
Try this:
var Date1 = "Thu Oct 22 00:00:00 GMT-04:00 2020"
var startDate = new Date(Date1);
// add it to startDate, using getDate()
startDate.setDate(startDate.getDate() + 10);
// now startDate will be 10 days later:
startDate; // Sun Nov 01 00:00:00 GMT-04:00 2020
// if you want an entirely new Date object, then instantiate a new one:
var Enddate = new Date(startDate);
If you want two different variables, then you can use the approach similar to what you tried, like so:
var Date1 = "Thu Oct 22 00:00:00 GMT-04:00 2020"
var startDate = new Date(Date1), second = new Date(Date1); // we're using another temporary variable
// add the days
second.setDate(second.getDate() + 10);
// now use Enddate with this
var Enddate = new Date(second);
Enddate; // Sun Nov 01 00:00:00 GMT-04:00 2020
You can't just add a number to a Date object to get a new date.
You can add to a date by:
getting the current day of the month with getDate()
adding a number of days to that result
setting the new date with setDate()
const Date1 = "Thu Oct 22 00:00:00 GMT-04:00 2020";
const addDays = 10;
const startDate = new Date(Date1);
const startDays = startDate.getDate();
const newDate = new Date(startDate);
newDate.setDate(startDays + addDays);
console.log('startDate:', startDate.toISOString());
console.log('newDate:', newDate.toISOString());
Note:
Passing a string into the Date constructor is discouraged, as it produces inconsistent results across browsers.
It is better to pass in the individual date and time values:
const Date1 = new Date(2020, 9, 22, 0, 0, 0);

How to get current month datas from mysql using javascript?

I have table of records and need to get only current month records.
CODE:
let startDate = req.body.startDate
let endDate = req.body.endDate
let result = await caseRegistration.findByDate({ pathology_id : req.body.pathology_id,
created_at: {
'>=': new Date(startDate),
'<=': new Date(endDate)
}
})
Above code I am passing particular dates to get records. But my requirement is If request doesn't have any date then I want to get only current month data. Can you please help me?
var date = new Date();
var firstDay = new Date(date.getFullYear(),date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(),date.getMonth(), daysInMonth(date.getMonth()+1,
date.getFullYear()));
firstDay=>Tue Sep 01 2020 00:00:00 GMT+0530 (India Standard Time)
lastDay=> Wed Sep 30 2020 00:00:00 GMT+0530 (India Standard Time)
Please take care of timezone & date formate you want(it could be any)
If startDate and endDate are empty find first date and last date of current month by using this :
var date = new Date();
var firstDateOfCurrentMonth = new Date(date.getFullYear(), date.getMonth(), 1);
var endDateOfCurrentMonth = new Date(date.getFullYear(), date.getMonth() + 1, 0);
Now you can assign these dates to startDate and endDate
statDate=firstDateOfCurrentMonth;
endDate=endDateOfCurrentMonth;

new Date can't give me right time

startDate = "2019-03-07 (목) 12:00";
var year = startDate.slice(0,4);
var month = startDate.slice(5,7);
var day = startDate.slice(8,10);
var hour = startDate.slice(15,17);
var minute = startDate.slice(18,20);
var selEndDatetime = new Date(year, month, day, hour, minute);
console.log(selEndDatetime);
I want to see "Tue Mar 07 2019 12:00:00 GMT+0900 (한국 표준시)", but console shows me the message "Sun Apr 07 2019 12:00:00 GMT+0900 (한국 표준시)".
What is wrong this code and how can I modify it to get the desired output?
The month starts at 0. You need to parse month from string to integer and minus 1 when creating a date instance.
startDate = "2019-03-07 (목) 12:00";
var year = startDate.slice(0,4);
var month = parseInt(startDate.slice(5,7))
var day = startDate.slice(8,10);
var hour = startDate.slice(15,17);
var minute = startDate.slice(18,20);
var selEndDatetime = new Date(year, month - 1, day, hour, minute);
console.log(selEndDatetime);
You can simply pass the startDate string as an argument to the Date in order to create selEndDatetime
Code:
const startDate = '2019-03-07 (목) 12:00';
const selEndDatetime = new Date(startDate);
console.log(selEndDatetime);

Converting milliseconds to a date (jQuery/JavaScript)

I'm a bit of a rambler, but I'll try to keep this clear -
I'm bored, so I'm working on a "shoutbox", and I'm a little confused over one thing. I want to get the time that a message is entered, and I want to make sure I'm getting the server time, or at least make sure I'm not getting the local time of the user. I know it doesn't matter, since this thing won't be used by anyone besides me, but I want to be thorough. I've looked around and tested a few things, and I think the only way to do this is to get the milliseconds since January 1, 1970 00:00:00 UTC, since that'd be the same for everyone.
I'm doing that like so:
var time = new Date();
var time = time.getTime();
That returns a number like 1294862756114.
Is there a way to convert 1294862756114 to a more readable date, like DD/MM/YYYY HH:MM:SS?
So, basically, I'm looking for JavaScript's equivalent of PHP's date(); function.
var time = new Date().getTime(); // get your number
var date = new Date(time); // create Date object
console.log(date.toString()); // result: Wed Jan 12 2011 12:42:46 GMT-0800 (PST)
If you want custom formatting for your date I offer a simple function for it:
var now = new Date;
console.log( now.customFormat( "#DD#/#MM#/#YYYY# #hh#:#mm#:#ss#" ) );
Here are the tokens supported:
token: description: example:
#YYYY# 4-digit year 1999
#YY# 2-digit year 99
#MMMM# full month name February
#MMM# 3-letter month name Feb
#MM# 2-digit month number 02
#M# month number 2
#DDDD# full weekday name Wednesday
#DDD# 3-letter weekday name Wed
#DD# 2-digit day number 09
#D# day number 9
#th# day ordinal suffix nd
#hhhh# 2-digit 24-based hour 17
#hhh# military/24-based hour 17
#hh# 2-digit hour 05
#h# hour 5
#mm# 2-digit minute 07
#m# minute 7
#ss# 2-digit second 09
#s# second 9
#ampm# "am" or "pm" pm
#AMPM# "AM" or "PM" PM
And here's the code:
//*** This code is copyright 2002-2016 by Gavin Kistner, !#phrogz.net
//*** It is covered under the license viewable at http://phrogz.net/JS/_ReuseLicense.txt
Date.prototype.customFormat = function(formatString){
var YYYY,YY,MMMM,MMM,MM,M,DDDD,DDD,DD,D,hhhh,hhh,hh,h,mm,m,ss,s,ampm,AMPM,dMod,th;
YY = ((YYYY=this.getFullYear())+"").slice(-2);
MM = (M=this.getMonth()+1)<10?('0'+M):M;
MMM = (MMMM=["January","February","March","April","May","June","July","August","September","October","November","December"][M-1]).substring(0,3);
DD = (D=this.getDate())<10?('0'+D):D;
DDD = (DDDD=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][this.getDay()]).substring(0,3);
th=(D>=10&&D<=20)?'th':((dMod=D%10)==1)?'st':(dMod==2)?'nd':(dMod==3)?'rd':'th';
formatString = formatString.replace("#YYYY#",YYYY).replace("#YY#",YY).replace("#MMMM#",MMMM).replace("#MMM#",MMM).replace("#MM#",MM).replace("#M#",M).replace("#DDDD#",DDDD).replace("#DDD#",DDD).replace("#DD#",DD).replace("#D#",D).replace("#th#",th);
h=(hhh=this.getHours());
if (h==0) h=24;
if (h>12) h-=12;
hh = h<10?('0'+h):h;
hhhh = hhh<10?('0'+hhh):hhh;
AMPM=(ampm=hhh<12?'am':'pm').toUpperCase();
mm=(m=this.getMinutes())<10?('0'+m):m;
ss=(s=this.getSeconds())<10?('0'+s):s;
return formatString.replace("#hhhh#",hhhh).replace("#hhh#",hhh).replace("#hh#",hh).replace("#h#",h).replace("#mm#",mm).replace("#m#",m).replace("#ss#",ss).replace("#s#",s).replace("#ampm#",ampm).replace("#AMPM#",AMPM);
};
You can simply us the Datejs library in order to convert the date to your desired format.
I've run couples of test and it works.
Below is a snippet illustrating how you can achieve that:
var d = new Date(1469433907836);
d.toLocaleString(); // expected output: "7/25/2016, 1:35:07 PM"
d.toLocaleDateString(); // expected output: "7/25/2016"
d.toDateString(); // expected output: "Mon Jul 25 2016"
d.toTimeString(); // expected output: "13:35:07 GMT+0530 (India Standard Time)"
d.toLocaleTimeString(); // expected output: "1:35:07 PM"
Below is a snippet to enable you format the date to a desirable output:
var time = new Date();
var time = time.getTime();
var theyear = time.getFullYear();
var themonth = time.getMonth() + 1;
var thetoday = time.getDate();
document.write("The date is: ");
document.write(theyear + "/" + themonth + "/" + thetoday);
Try using this code:
var datetime = 1383066000000; // anything
var date = new Date(datetime);
var options = {
year: 'numeric', month: 'numeric', day: 'numeric',
};
var result = date.toLocaleDateString('en', options); // 10/29/2013
See more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
Try using this code:
var milisegundos = parseInt(data.replace("/Date(", "").replace(")/", ""));
var newDate = new Date(milisegundos).toLocaleDateString("en-UE");
Enjoy it!
so you need to pass that var time after getTime() into another new Date()
here is my example:
var time = new Date()
var time = time.getTime()
var newTime = new Date(time)
console.log(newTime)
//Wed Oct 20 2021 15:21:12 GMT+0530 (India Standard Time)
here output is my datetime standard format for you it will be in country format
if you want it in another format then you can apply another date function on var newTime
like
var newTime = new Date(time).toDateString()
console.log(newTime)
//Wed Oct 20 2021
Try this one :
var time = new Date().toJSON();
One line code.
var date = new Date(new Date().getTime());
or
var date = new Date(1584120305684);
/Date(1383066000000)/
function convertDate(data) {
var getdate = parseInt(data.replace("/Date(", "").replace(")/", ""));
var ConvDate= new Date(getdate);
return ConvDate.getDate() + "/" + ConvDate.getMonth() + "/" + ConvDate.getFullYear();
}
Assume the date as milliseconds date is 1526813885836, so you can access the date as string with this sample code:
console.log(new Date(1526813885836).toString());
For clearness see below code:
const theTime = new Date(1526813885836);
console.log(theTime.toString());
use datejs
new Date().toString('yyyy-MM-d-h-mm-ss');

Categories