how to get number of days from angularjs - javascript

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

Related

remove T and Z in date field in Javascript

I have this date field in UTC format say
dt1 = "2020-03-27T16:59:57Z"
and another date field in local format say
dt2 = "2020-03-27 16:00:00"
I need to find the differnece in minutes between dt1 and dt2. Basically I need to remove the T and Z in dt1 datefield and do the difference.
Here is what I tried:
var diff = (dt1 - dt2) / 1000;
diff /= 60;
return Math.abs(Math.round(diff));
But it return NaN as output. please provide a fix for this!
You should transform the strings to dates so that you can perform operations with the dates:
var dt1 = new Date("2020-03-27T16:59:57Z".replace('T', ' ').replace('Z', ''))
var dt2 = new Date("2020-03-27 16:00:00")
function calcDifference(dt1, dt2) {
var diff = (dt1 - dt2) / 1000;
diff /= 60;
return Math.abs(Math.round(diff));
}
console.log(calcDifference(dt1, dt2));

Calculate the day difference between two time

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.

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

Convert a String to a Single Date in Javascript

I have an input text that has a combination of date and time and display like this
04/01/2015 8:48PM
How can i convert this string to a date using the function new Date() in javascript? not output is shown
Here is what i've tried so far, i can only convert the date not the time.
HTML
<form name="frm1" >
<h3>Check in Date:</h3>
<input type="text" value="" class="datetimepicker_mask" name="dtp1" /><br><br>
<h3>Check out Date:</h3>
<input type="text" value="" class="datetimepicker_mask" name="dtp2" /><br><br>
<input type="button" onclick="computeDate()" value="Compute Difference" />
<br><b>No of days: </b>
<span id="date_difference"></span>
</form>
JAVSCRIPT
function computeDate() {
var dateTime1 = document.frm1.dtp1.value;
var dateTime2 = document.frm1.dtp2.value;
var startDate = new Date(dateTime1);
var endDate = new Date(dateTime2);
var timeDiff = Math.abs(endDate.getTime() - startDate.getTime());
if (timeDiff == 0) {
timeDiff = 1;
}
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
var total = parseFloat(diffDays) * parseFloat(roomRate);
document.getElementById("date_difference").innerHTML = diffDays;
document.getElementById("date_difference").style.visibility = "visible";
}
If the date format is always the same, create a convience function that converts the date to a Date object
function convert(date) {
var dateArr = date.split(/[\s\/\:]/);
if (dateArr[4].toLowerCase().indexOf('pm') != -1)
dateArr[3] = (+dateArr[3]) + 12;
dateArr[4] = dateArr[4].replace(/\D/g,'');
dateArr[0]--;
return new Date(dateArr[2], dateArr[0], dateArr[1], dateArr[3], dateArr[4]);
}
FIDDLE
Here is an answer that will both solve this and make development easier. This suggestion will require an extra library for addressing such issues as you are having here- time, but you'll likely find it beneficial when working with JavaScript dates in general. It already looks like you're writing manual date functions. Abstract them away with robust libraries for solving these same issues that have come up again and again. Using date.js, here is how easy this becomes
Date.parse('04/01/2015 8:48PM ')
JSFiddle Example
You can create the Date object after parsing the dateString
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
you can use the parseDate function as following
var testDate = "04/01/2015 8:48PM";
console.log(parseDate(testDate));
function parseDate(dateStr){
var dateTime = dateStr.split(/\/| |:|(?=[PA])/);
for(var i=0; i<5; i++){
dateTime[i] = parseInt(dateTime[i]);
}
if(dateTime[5] == "PM"){
dateTime[3] += 12;
}
return new Date(dateTime[2], dateTime[1], dateTime[0], dateTime[3], dateTime[4]);
}
Try it at JSFiddle

Moment JS gives wrong date when I use diff

I've been working to get the difference of two dates using moment JS.
test1 = new Date("01/12/2015")
test2 = new Date("12/12/2014")
get_diff = moment.duration(moment(test1,"DD/MM/YYYY").diff(moment(test2,"DD/MM/YYYY")))
result_diff = get_diff.asDays()
console.log result_diff
It gives: 365. It supposed to give 31 days.
You don't need to use durations for this and also no need to convert to "DD/MM/YYYY" format. Just use diff method with "days" as the second parameter:
var test1 = new Date("01/12/2015");
var test2 = new Date("12/12/2014");
var result_diff = moment(test1).diff(moment(test2), "days"); // 31
You should be instantiating the moment objects with the strings themselves:
var test1 = moment('01/12/2015', 'MM/DD/YYYY');
var test2 = moment('12/12/2014', 'MM/DD/YYYY');
var get_diff = moment.duration(test1.diff(test2));
var result_diff = get_diff.asDays();
I suppose you should change your code to get days difference
var date1 = new Date("01/12/2015")
var date2 = new Date("12/12/2014")
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
The way you have it written, you should not be using JS date objects and you have the month and days switched.
test1 = "01/12/2015";
test2 = "12/12/2014";
get_diff = moment.duration(moment(test1,"MM/DD/YYYY").diff(moment(test2,"MM/DD/YYYY")))
result_diff = get_diff.asDays()
console.log(result_diff)

Categories

Resources