Calculate the day difference between two time - javascript

I have two date format and I need to calculate the hour difference between both.
First date is current date.
Second Date is in below format :
var depDate = 25092018 //ddmmyyyy
var depTime = 08:35 //hh:mm
new Date function doesn't take date in format ddmmyyyy. How can input depDate in new Date function
I want to check the difference between current date and depDate.
Can anybody help ?

Your date in variable depDate hasn't valid format. You need to validate format of it using regex in .replace(). Then use Date.prototype.getTime() getting numeric value of date.
var depDate = "25092018";
var depTime = "08:35";
var dateStr = depDate.replace(/(\d{2})(\d{2})(\d{4})/, "$3-$2-$1")+"T"+depTime;
// dateStr => 2018-09-25T08:35
var timeDiff = Math.abs(new Date(dateStr).getTime() - new Date().getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
// 1000 => to converting millisecond to second
// 3600 => to converting second to hour
// 24 => to converting hour to day
console.log(diffDays);

If you are using moment module, it would be much easy. Code a below:
let moment = require('moment');
let depDate = "27092018" //ddmmyyyy
let depTime = "08:35" //hh:mm
let date = moment(depDate, "DDMMYYYY").add(moment(depTime,"HH:mm"))
let difference = moment.duration(moment().diff(date)).asHours();
console.log(difference); // This would be the difference in hours.

Related

how to get number of days from angularjs

how to get number of days between two dates but its not working i think my date format not correct but how to change date format and get number of days
$scope.ChangeDate = function () {
var oneDay = 24 * 60 * 60 * 1000;
var firstDate = $scope.Current.PlainnedStart;
var secondDate = $scope.Current.PlainnedEnd;
if (!angular.isUndefined(firstDate) && !angular.isUndefined(secondDate)) {
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime()) / (oneDay)));
alert(diffDays);
$scope.Current.NOD = ++diffDays;
}
}
enter image description here
<input type="text" onchange="angular.element(this).scope().ChangeDate()"
id="date" ng-model="Current.PlainnedStart"
class="floating-label mdl-textfield__input" placeholder="">
you can use
<input class="form-control" ng-model="day1" ng-blur="getDate(day1)" type="text" readonly />
$scope.getDate= function (date) {
var dates = new Date();
console.log(dates);
}
you can easily manage with momentjs with date evens
var a = moment('2018-04-17T07:00:00.000Z');
var b = moment('2018-04-27T07:00:00.000Z');
var days = b.diff(a, 'days');
http://momentjs.com/
or with Javascript
var a = new Date("2018-04-17T07:00:00.000Z");
var b = new Date("2018-04-27T07:00:00.000Z");
var dayDif = (a - b) / 1000 / 60 / 60 / 24;
You should convert both dates into the JavaScript Date object. From what I can see, the inputs from both date inputs are in 'dd-mm-yyyy' format, and this will cause some problems if you try to directly convert it into the Date object. Instead, you should convert it to 'yyyy-mm-dd' before converting it to a date object.
Then, you can calculate the difference between both dates.
const str1 = '17-04-2019';
const str2 = '20-04-2019';
const toDate = dateStr => {
const parts = dateStr.split('-');
return new Date(parts[2], parts[1] - 1, parts[0]);
}
const diff = Math.floor((toDate(str2) - toDate(str1) ) / 86400000);
console.log(diff)
As mentioned in the previous answer above you can either split the string to get the values. Or change it like below
Ex:Suppose my date string is
var str1 = '17-Apr-2019';
var str2 = '20-Apr-2019';
var diff = Math.abs(new Date(str2).getDate() - new Date(str1).getDate());
console.log(diff)
Output => 3
Or if you dont want any code changes.
Change the format of the datepicker to (mm-dd-yyyy) you will get same output

how to use Date.toLocaleString() with changing timezones

I converted my start and end date to .ToLocalString and now I am trying to use math.abs to calculate difference between start and end date in numbers but its Value is NaN. Any suggestions on how to apply Math.abs in this situation are appreciated.
Note: Start date will be in EDT and EndDate will be in EST. But they
might or might not be in same timezone.
var startDate1 = new Date(homeCtrl.createStartDate);
var startDate = startDate1.toLocaleString();
var endDate1 = new Date(homeCtrl.createEndDate);
var endDate = endDate1.toLocaleString();
var timeDiff = Math.abs(endDate - startDate); //This is NaN
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); // Here it will add 1 extra day. Example: 11/06/2018 - 11/04/2018 = 2 days but this gives 3days are timezone change on 11/04/2018 and thats the issue.
I would use the unix timestamp.
var startDate1 = new Date(homeCtrl.createStartDate);
var startDate = startDate1.getTime();
var endDate1 = new Date(homeCtrl.createEndDate);
var endDate = endDate1.getTime();
var timeDiff = Math.abs(endDate - startDate);

JavaScript, how to create difference of date with moment.js

I am having a problem with creating an error message on a page where there is a "from date:", and a "to date:". If the difference between the two dates is greater than or equal to 60 days, I have to put up an error message.
I am trying to use moment.js and this is what my code is looking like now. It was recommended that I use it in knockout validation code. this is what it looks like right now:
var greaterThan60 = (moment().subtract('days', 60) === true) ? "The max range for from/to date is 60 days." : null;
I am still not sure how to make it greater than 60 days, not just equal to 60 days. This is what my boss gave me to help.
Reference site for moment().subtract
moment.js provides a diff() method to find difference between dates. please check below example.
var fromDate = 20180606;
var toDate = 20180406;
var dif = moment(fromDate, 'YYYYMMDD').diff(moment(toDate, 'YYYYMMDD'),'days')
console.log(dif) // 61
subtract returns a new moment object. So checking for true always returns false. You can use range and diff to calculate a diff in days and check that:
let start = moment('2016-02-27');
let end = moment('2016-03-02');
let range = moment.range(start, end);
let days = range.diff('days');
let error = null;
if (days > 60) {
error = "The max range for from/to date is 60 days.";
}
You Can try this.
var date = Date.parse("2018-04-04 00:00:00");
var selectedFromDate = new Date(date);
var todayDate = new Date();
var timedifference = Math.abs(todayDate.getTime() - selectedFromDate.getTime());
var daysDifference = Math.ceil(timedifference/(1000 * 3600 * 24));
just use if else loop for greater than 60 days validation.
if(daysDifference > 60)
{
alert("From Date should be less than 2 months");
}
Use the .isSameOrAfter function to compare if the end value is greater than or equal to the start value plus sixty days. Example:
var greaterThan60 = toDate.isSameOrAfter(startDate.add(60, 'days'));
where toDate is your end time as a moment object and startDate is the start time as a moment object. If the end date is greater than or equal to 60 days after the start date, greaterThan60 will be true.
References:
isSameOrAfter
add

How to get current day count of the quarter [duplicate]

I have two input dates taking from Date Picker control. I have selected start date 2/2/2012 and end date 2/7/2012. I have written following code for that.
I should get result as 6 but I am getting 5.
function SetDays(invoker) {
var start = $find('<%=StartWebDatePicker.ClientID%>').get_value();
var end = $find('<%=EndWebDatePicker.ClientID%>').get_value();
var oneDay=1000 * 60 * 60 * 24;
var difference_ms = Math.abs(end.getTime() - start.getTime())
var diffValue = Math.round(difference_ms / oneDay);
}
Can anyone tell me how I can get exact difference?
http://momentjs.com/ or https://date-fns.org/
From Moment docs:
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // =1
or to include the start:
a.diff(b, 'days')+1 // =2
Beats messing with timestamps and time zones manually.
Depending on your specific use case, you can either
Use a/b.startOf('day') and/or a/b.endOf('day') to force the diff to be inclusive or exclusive at the "ends" (as suggested by #kotpal in the comments).
Set third argument true to get a floating point diff which you can then Math.floor, Math.ceil or Math.round as needed.
Option 2 can also be accomplished by getting 'seconds' instead of 'days' and then dividing by 24*60*60.
If you are using moment.js you can do it easily.
var start = moment("2018-03-10", "YYYY-MM-DD");
var end = moment("2018-03-15", "YYYY-MM-DD");
//Difference in number of days
moment.duration(start.diff(end)).asDays();
//Difference in number of weeks
moment.duration(start.diff(end)).asWeeks();
If you want to find difference between a given date and current date in number of days (ignoring time), make sure to remove time from moment object of current date as below
moment().startOf('day')
To find difference between a given date and current date in number of days
var given = moment("2018-03-10", "YYYY-MM-DD");
var current = moment().startOf('day');
//Difference in number of days
moment.duration(given.diff(current)).asDays();
Try this Using moment.js (Its quite easy to compute date operations in javascript)
firstDate.diff(secondDate, 'days', false);// true|false for fraction value
Result will give you number of days in integer.
Try:
//Difference in days
var diff = Math.floor(( start - end ) / 86400000);
alert(diff);
This works for me:
const from = '2019-01-01';
const to = '2019-01-08';
Math.abs(
moment(from, 'YYYY-MM-DD')
.startOf('day')
.diff(moment(to, 'YYYY-MM-DD').startOf('day'), 'days')
) + 1
);
I made a quick re-usable function in ES6 using Moment.js.
const getDaysDiff = (start_date, end_date, date_format = 'YYYY-MM-DD') => {
const getDateAsArray = (date) => {
return moment(date.split(/\D+/), date_format);
}
return getDateAsArray(end_date).diff(getDateAsArray(start_date), 'days') + 1;
}
console.log(getDaysDiff('2019-10-01', '2019-10-30'));
console.log(getDaysDiff('2019/10/01', '2019/10/30'));
console.log(getDaysDiff('2019.10-01', '2019.10 30'));
console.log(getDaysDiff('2019 10 01', '2019 10 30'));
console.log(getDaysDiff('+++++2019!!/###10/$$01', '2019-10-30'));
console.log(getDaysDiff('2019-10-01-2019', '2019-10-30'));
console.log(getDaysDiff('10-01-2019', '10-30-2019', 'MM-DD-YYYY'));
console.log(getDaysDiff('10-01-2019', '10-30-2019'));
console.log(getDaysDiff('10-01-2019', '2019-10-30', 'MM-DD-YYYY'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
Also you can use this code: moment("yourDateHere", "YYYY-MM-DD").fromNow(). This will calculate the difference between today and your provided date.
// today
const date = new Date();
// tomorrow
const nextDay = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
// Difference in time
const Difference_In_Time = nextDay.getTime() - date.getTime();
// Difference in Days
const Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);

Javascript and mySQL dateTime stamp difference

I have a mySQL database in which I store the time in this format automatically:
2015-08-17 21:31:06
I am able to retrieve this time stamp from my database and bring it into javascript. I want to then get the current date time in javascript and determine how many days are between the current date time and the date time I pulled from the database.
I found this function when researching how to get the current date time in javascript:
Date();
But it seems to return the date in this format:
Tue Aug 18 2015 10:49:06 GMT-0700 (Pacific Daylight Time)
There has to be an easier way of doing this other than going character by character and picking it out from both?
You can build a new date in javascript by passing the data you receive from your backend as the first argument.
You have to make sure that the format is an accepted one. In your case we need to replace the space with a T. You may also be able to change the format from the back end.
Some good examples are available in the MDN docs.
var d = new Date("2015-08-17T21:31:06");
console.log(d.getMonth());
To calculate the difference in days you could do something like this:
var now = new Date();
var then = new Date("2015-08-15T21:31:06");
console.log((now - then)/1000/60/60/24);
You can select the difference directly in your query:
SELECT DATEDIFF(now(), myDateCol) FROM myTable;
the Date object has a function called getTime(), which will give you the current timestamp in milliseconds. You can then get the diff and convert to days by dividing by (1000 * 3600 * 24)
e.g.
var date1 = new Date()
var date2 = new Date()
var diffInMs = date2.getTime() - date1.getTime()
var diffInDays = diffInMs/(1000*3600*24)
Since none of the other answer got it quite right:
var pieces = "2015-08-17 21:31:06".split(' ');
var date = pieces[0].split('-');
var time = pieces[1].split(':');
var yr = date[0], mon = date[1], day = date[2];
var hour = time[0], min = time[1], sec = time[2];
var dateObj = new Date(yr, mon, day, hr, min, sec);
//if you want the fractional part, omit the call to Math.floor()
var diff = Math.floor((Date.now() - dateObj.getTime()) / (1000 * 60 * 60 * 24));
Note that none of this deals with the timezone difference between the browser and whatever you have stored in the DB. Here's an offset example:
var tzOff = new Date().getTimezoneOffset() * 60 * 1000; //in ms

Categories

Resources