I created a function to check the difference between a particular date and the current date, everything is working perfectly for past dates. But, when it comes to future dates, it gives the correct difference eg. the 18th of May is two days after the 16th of May, so the difference is 2, but I don't know if it's two days before or two days after. I cannot differentiate between future dates and past dates, whether the date is in the past or in the future.
here is my code:
function GetDateDiff(previousDate, previousTime) {
let today = new Date();
let dd = String(today.getDate()).padStart(2, "0");
let mm = String(today.getMonth() + 1).padStart(2, "0"); //January is 0!
let yyyy = today.getFullYear();
let currentDate = mm + "/" + dd + "/" + yyyy; // this will give you the current date
let previousMinutes = previousTime.split(":")[1];
let previousSeconds = previousTime.split(":")[2];
let previousHours = previousTime.split(":")[0];
let timePeriod = "seconds"; // timePeriod is the current unit of mesearement whether in seconds hours or days
let timeInNumber = "0"; //timeInNumber is the number infront of the timeperiod eg the 40 in 40 minites is the timeInNumber
let dateObj = new Date();
// this is to set the appropriate seconds, minutes and hours
if (currentDate == previousDate) {
if (dateObj.getHours() == previousHours) {
if (dateObj.getMinutes() == previousMinutes) {
timeInNumber = dateObj.getSeconds() - previousSeconds;
timePeriod = "Second";
} else {
timeInNumber = dateObj.getMinutes() - previousMinutes;
timePeriod = "Minute";
}
} else {
timeInNumber = dateObj.getHours() - previousHours;
timePeriod = "Hour";
// timePeriod =dateObj.getHours();
}
} else {
const previousDateDifferential = new Date(previousDate);
const currentDateDifferential = new Date(currentDate);
const diffrenceInDate = Math.abs(
currentDateDifferential - previousDateDifferential
);
// this is to calculate the diffrence in days, weeks, months and years
const diffDays = Math.ceil(diffrenceInDate / (1000 * 60 * 60 * 24));
const diffWeeks = Math.ceil(diffrenceInDate / (1000 * 60 * 60 * 24 * 7));
const diffMonths = Math.ceil(diffrenceInDate / (1000 * 60 * 60 * 24 * 7 * 4));
const diffyears = Math.ceil(diffrenceInDate / (1000 * 60 * 60 * 24 * 7 * 4 * 12));
// this is to set the appropriate days, weeks, months and years
if (diffDays <= 30) {
timeInNumber = diffDays;
timePeriod = "Day";
} else if (diffDays > 30 && diffWeeks <= 4) {
timeInNumber = diffWeeks;
timePeriod = "Week";
} else if (diffWeeks > 4 && diffMonths <= 12) {
timeInNumber = diffMonths - 2;
timePeriod = "Month";
} else if (diffMonths > 12) {
timeInNumber = diffyears - 1;
timePeriod = "Year";
}
}
if (timeInNumber > 1) {
timePeriod += "s"// this is to ad 's' at the end of the time period if the time period is more than 1
}
return `${timeInNumber} ${timePeriod} Ago`;
}
if I write GetDateDiff("05/14/2022", "00:00:00") // result will be 2 days ago
if I write GetDateDiff("05/18/2022", "00:00:00") // result will still be 2 days ago, how can i make it 2 days later or check that the date is in the future
The best tip was given already: use > and < to compare dates. Here is an example to get you started:
// function GetDateDiff to get the difference to the current date including negative values
function GetDateDiff(date) {
// get current date
var currentDate = new Date();
// get the difference between the current date and the date passed in
var diff = date.getTime() - currentDate.getTime();
// Build string prefix for negative and positive dates
var diffString = diff < 0 ? "In the Past: " : "In the Future: ";
// get the absolute value of the difference
diff = Math.abs(diff);
// get the days, hours, minutes, and seconds from the difference
var days = Math.floor(diff / (1000 * 60 * 60 * 24));
var hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((diff % (1000 * 60)) / 1000);
// return the difference in days, hours, minutes, and seconds
return diffString + days + " days, " + hours + " hours, " + minutes + " minutes, " + seconds + " seconds";
}
// example usage
var date = new Date(2020, 0, 1, 0, 0, 0, 0);
var diff = GetDateDiff(date);
alert(diff);
var date = new Date(2024, 0, 1, 0, 0, 0, 0);
var diff = GetDateDiff(date);
alert(diff);
function GetDateDiff(previousDate, previousTime) {
let today = new Date();
let dd = String(today.getDate()).padStart(2, "0");
let mm = String(today.getMonth() + 1).padStart(2, "0"); //January is 0!
let yyyy = today.getFullYear();
let currentDate = mm + "/" + dd + "/" + yyyy; // this will give you the current date
let previousMinutes = previousTime.split(":")[1];
let previousSeconds = previousTime.split(":")[2];
let previousHours = previousTime.split(":")[0];
let timePeriod = "seconds"; // timePeriod is the current unit of mesearement whether in seconds hours or days
let timeInNumber = "0"; //timeInNumber is the number infront of the timeperiod eg the 40 in 40 minites is the timeInNumber
let timeWord = "Ago"
let dateObj = new Date();
// this is to set the appropriate seconds, minutes and hours
if (currentDate == previousDate) {
if (dateObj.getHours() == previousHours) {
if (dateObj.getMinutes() == previousMinutes) {
timeInNumber = dateObj.getSeconds() - previousSeconds;
timePeriod = "Second";
} else {
timeInNumber = dateObj.getMinutes() - previousMinutes;
timePeriod = "Minute";
}
} else {
timeInNumber = dateObj.getHours() - previousHours;
timePeriod = "Hour";
// timePeriod =dateObj.getHours();
}
}
else {
const previousDateDifferential = new Date(previousDate);
const currentDateDifferential = new Date(currentDate);
const diffrenceInDate = Math.abs(
currentDateDifferential - previousDateDifferential
);
// this is to calculate the diffrence in days, weeks, months and years
const diffDays = Math.ceil(diffrenceInDate / (1000 * 60 * 60 * 24));
const diffWeeks = Math.ceil(diffrenceInDate / (1000 * 60 * 60 * 24 * 7));
const diffMonths = Math.ceil(diffrenceInDate / (1000 * 60 * 60 * 24 * 7 * 4));
const diffyears = Math.ceil(diffrenceInDate / (1000 * 60 * 60 * 24 * 7 * 4 * 12));
// this is to set the appropriate days, weeks, months and years
if (diffDays <= 30) {
timeInNumber = diffDays;
timePeriod = "Day";
} else if (diffDays > 30 && diffWeeks <= 4) {
timeInNumber = diffWeeks;
timePeriod = "Week";
} else if (diffWeeks > 4 && diffMonths <= 12) {
timeInNumber = diffMonths - 2;
timePeriod = "Month";
} else if (diffMonths > 12) {
timeInNumber = diffyears - 1;
timePeriod = "Year";
}
if (currentDate < previousDate) {
timeWord = "Later"
}else {
timeWord = "Ago"
}
}
if (timeInNumber > 1) {
timePeriod += "s"// this is to ad 's' at the end of the time period if the time period is more than 1
}
return `${timeInNumber} ${timePeriod} ${timeWord}`;
}
GetDateDiff("05/14/2022", "00:00:00") // result will be 2 days ago
GetDateDiff("05/18/2022", "00:00:00") // result will be 2 days later
I am having a three String or Float values say 9.30, 8.00 and 0.40 as Total_hour, Paid_hour, Extra_hour
These should be actually 9 hours 30 minutes, 8 hours 0 minutes, 0 hours 40 minutes.
Question 1) How to convert 9.30 to 9 hours 30 minutes
Question 2) Later want to Subtract and get Remaining Hour = Total_hour-Paid_Hour-Extra_hour
Later the answer Remaining Hour should be in float
This should work.
You just need to convert to ms:
let timefloat = 9.3;
function convertToMs(timefloat) {
// Get the minutes portion
let remainder = timefloat % 1;
// Convert into ms
let minutes = remainder * 100 * 60 * 1000;
// Get the number of hours and convert to ms
let hours = (timefloat - remainder) * 60 * 60 * 1000;
return minutes + hours;
}
// Convert back to float format
function convertToFloat(date) {
let hours = date.getUTCHours();
let mins = date.getUTCMinutes();
return hours + (mins / 100);
}
// Log the result
console.log(new Date(convertToMs(9.3)).toUTCString());
console.log(new Date(convertToMs(8.0)).toUTCString());
console.log(new Date(convertToMs(9.3) - convertToMs(8.0)).toUTCString());
let diff = convertToMs(9.3) - convertToMs(8.0);
console.log(convertToFloat(new Date(diff)))
The following javascript snippet converts a given float to hours and minutes. Source float to time
function convertNumToTime(number) {
// Check sign of given number
var sign = (number >= 0) ? 1 : -1;
// Set positive value of number of sign negative
number = number * sign;
// Separate the int from the decimal part
var hour = Math.floor(number);
var decpart = number - hour;
var min = 1 / 60;
// Round to nearest minute
decpart = min * Math.round(decpart / min);
var minute = Math.floor(decpart * 60) + '';
// Add padding if need
if (minute.length < 2) {
minute = '0' + minute;
}
// Add Sign in final result
sign = sign == 1 ? '' : '-';
// Concate hours and minutes
time = sign + hour + ':' + minute;
return time;
}
console.log(convertNumToTime(11.15));
Output
11:09
First convert the number in minutes and then do your subtraction. Then convert your output to hours.
var Total_hour = '9.30',
Paid_hour = '8.00',
Extra_hour = '0.40';
var conversionInMinutes = hour => Math.floor(hour) * 60 + (hour - (Math.floor(hour))) * 100;
var conversionInHours = min => Math.floor( min/60 ) + min % 60 / 100;
var Remaining_hour = conversionInMinutes(Total_hour) - conversionInMinutes(Paid_hour) - conversionInMinutes(Extra_hour);
console.log(conversionInHours(Remaining_hour).toFixed(2));
function doTime(input)
{
input = input.toString()
inputs = input.split(".")
return (inputs[0] + "Hour and" + inputs[1] + "minutes")
}
doTime("9:22")
function substract2
function subtract2(a , b){
a = input.toString()
arrayA = input.split(".")
b = input.toString()
arrayB = input.split(".")
h = parseInt(arrayB[0]) - parseInt(arrayA[0])
h <0 ? h+=12/*or 24*/ :h=h
m = parseInt(arrayB[1]) - parseInt(arrayA[1])
if(m<0){h-- ; m+=60}
return h.toString() + ":" + m.toString()
}
I have a list of data displayed using ng-repeat.
I'm thinking that if it is possible to return HTML tag, it would be easier.
Like this:
return '<span class="redHour">'+diffHours+'</span>;
but this does't work.
I have this HTML code:
<li><p class="table-data3" id="normal-hour">{{RT(order.purchaseTime)}}</p> </li>
If the calculated purchase time is less than 4 I want the color of the p becomes red.
Function
$scope.RT = function(order) {
var timeDifference;
var currentDate;
var deadLine;
var diffDays;
var diffHours;
var diffMinutes;
currentDate = new Date();
deadLine = new Date(parseInt(order)); // setting purchase time Date Object
deadLine = new Date(deadLine.setDate(deadLine.getDate()+1)); // setting purchase time Date Object + 1 day
timeDifference = (deadLine.getTime()) - (currentDate.getTime()); // deadline data minus current date
var diffDays = Math.floor(timeDifference / (1000 * 60 * 60 * 24));
var diffHours = Math.floor(timeDifference / (1000 * 60 * 60));
var diffMinutes = Math.floor((timeDifference-(diffHours*(1000 * 60 * 60))) / (1000 * 60));
if(diffHours <= 4){
//WHAT SHOULD I PUT HERE?
}
if (diffHours == 0 && diffMinutes > 0) {
return diffMinutes +" Mins";
}else if (diffHours <= 0) {
diffHours = 0;
return diffHours;
}else if (diffHours == 1) {
return diffHours + " Hour";
}else {
return diffHours +" Hours";
}
}
THANK YOU!
You can implement filter:
app.filter('hoursNow', function () {
return function (ts) {
var timeDifference = Date.now() - ts;
var diffDays = Math.floor(timeDifference / (1000 * 60 * 60 * 24));
var diffHours = Math.floor(timeDifference / (1000 * 60 * 60));
var diffMinutes = Math.floor((timeDifference-(diffHours*(1000 * 60 * 60))) / (1000 * 60));
if (diffHours < 4) {
return '<span class="red">'+diffHours+'hrs</span>';
}
return '<span class="green">'+diffHours+'hrs</span>';
}
});
And use it with ng-bind-html:
<p ng-bind-html="order.purchaseTime | hoursNow"></p>
Fiddle
Your $scope.RT function could return a CSS class and the value itself. You can add the CSS class to the p tag in your template to change the styling according to the value.
Modify your method to return object and use ngInit directive. Your method can return Object with properties {'text': String, 'display_red': Boolean}.
<div ng-repeat="item in date" ng-init="item_info = RT(item.purchaseTime)">
<li ng-class="{inRed: item.displayRed}">
<span class="table-data3" id="normal-hour">{{item.text}}</span>
</li>
</div>
Also I've used ngClass directive to dynamically assign css class inRed, so you have to add such css class to.
Also below is modified if..else from $scope.RT function:
var result = {'displayRed': False};
if(diffHours <= 4){
result['displayRed'] = True;
}
if (diffHours == 0 && diffMinutes > 0) {
result['text'] = diffMinutes +" Mins";
}else if (diffHours <= 0) {
diffHours = 0;
result['text'] = diffHours;
}else if (diffHours == 1) {
result['text'] = diffHours + " Hour";
}else {
result['text'] = diffHours +" Hours";
}
return result
use ng-style in your DOM
<li><p class="table-data3" id="normal-hour" ng-style="setColor(order)">{{RT(order.purchaseTime)}}</p> </li>
in controller
$scope.setColor = function(order){
var color;
//Do your math
return{ 'background-color': color}
}
Currently working on jquery clone and datepicker where it will calulate the dates and it will check the overlaping dates. But if the click the less button the code works perfectly it was removing the row but it was not detecting the dates which was there in the cloned div. For example when the user select the date 10-01-1990 & 10-01-1995 for this the total was Total work experience 5 years 0 Months & in the cloned div if the user gave 10-01-1996 & 10-01-2015 so the total was Total work experience 25 years 0 Months. If the user click the lessbtn button the cloned one will remove but the total year was not detecting.
Here is the jquery code
$(document).on('change', ".datepicker", function (){
var valid=true;
$.each($('.datepicker'),function(){
if($(this).val()=="")
{
valid=false;
return false;
}
});
if(valid)
{
var dateStart=[];
var dateEnd=[];
$.each($('.datepicker'),function(){
if($(this).hasClass('startDate'))
dateStart.push($(this).val())
else
dateEnd.push($(this).val())
});
$.each($(dateStart),function(key,value){
var x = dateStart[key].split("-");
var y = dateEnd[key].split("-");
var failed = false;
var fromdate = new Date(x[2], x[0] - 1, x[1]);
var todate = new Date(y[2], y[0] - 1, y[1]);
var locDiffDays = parseInt((todate.getTime() - fromdate.getTime()) / (1000 * 60 * 60 * 24));
console.log(x);
console.log(y);
console.log(fromdate);
console.log(todate);
console.log(locDiffDays);
if(locDiffDays<0){
alert("To date " + dateEnd[key] + " should be greater then from date " + dateStart[key] );
console.log("invalid from and to dates"); failed = true; return false;
}
if(dateStart[key-1]){
var x1 = dateStart[key-1].split("-");
var y1 = dateEnd[key-1].split("-");
var fromdate1 = new Date(x1[2], x1[0] - 1, x1[1]);
var todate1 = new Date(y1[2], y1[0] - 1, y1[1]);
var locDiffDays1 = parseInt((todate1.getTime() - fromdate1.getTime()) / (1000 * 60 * 60 * 24));
console.log(x1);
console.log(y1);
console.log(fromdate1);
console.log(todate1);
console.log(locDiffDays1);
var locDiffDays2 = parseInt((fromdate.getTime() - fromdate1.getTime()) / (1000 * 60 * 60 * 24));
var locDiffDays3 = parseInt((todate.getTime() - todate1.getTime()) / (1000 * 60 * 60 * 24));
var locDiffDays4 = parseInt((fromdate.getTime() - todate1.getTime()) / (1000 * 60 * 60 * 24));
console.log("locDiffDays2: " + locDiffDays2);
if(locDiffDays2<0){
alert("From date " + dateStart[key] + " should be greater than previous from date " + dateStart[key-1] );
console.log("invalid from dates"); failed = true; return false;
}
if(locDiffDays3<0){
alert("To date " + dateStart[key] + " should be greater than previous To date " + dateStart[key-1] );
console.log("invalid from dates"); failed = true; return false;
}
if(locDiffDays4<0){
alert("From date " + dateStart[key] + " should be greater than previous To date " + dateEnd[key-1] );
console.log("invalid from dates"); failed = true; return false;
}
}
if(key == dateStart.length-1 && !failed){
var firstDate = dateStart[0].split('-');
firstDate = new Date(firstDate[2], firstDate[0] - 1, firstDate[1]);
var lastDate = dateEnd[dateEnd.length-1].split('-');
lastDate = new Date(lastDate[2], lastDate[0] - 1, lastDate[1]);
console.log(lastDate);
console.log(firstDate);
//var diffYears = (lastDate.getTime() - firstDate.getTime()) / (1000 * 60 * 60 * 24 * 365);
var diffMonths = monthDiff(firstDate, lastDate);
//diffYears = parseInt(''+diffYears);
var diffYears = diffMonths/12;
diffYears = parseInt(''+diffYears);
diffMonths = diffMonths - (diffYears * 12)
document.getElementById("txt_expy").innerHTML = diffYears + " years";
document.getElementById("txt_expm").innerHTML = diffMonths + " Months";
}
});
Kindly please suggest me.
I am confused here do i want to put any count or something so when the user click the less button the count should reduce one and the value should get detected. Kindly give me tips here
Hereis the fiddle Link
Thanks & Regards
Your issue is you are not calling any logic to update the difference while removing the cloned object. You wrote code for updating the difference only in datepicker.change event.
Demo
Updated code:
$(document).on('change', ".datepicker", function() {
updateDiff()
});
$(document).on('click', ".btn_less1", function() {
var len = $('.cloned-row3').length;
if (len > 1) {
$(this).closest(".btn_less1").parent().parent().parent().remove();
updateDiff();
}
});
function updateDiff() {
var valid = true;
$.each($('.datepicker'), function() {
if ($(this).val() == "") {
valid = false;
return false;
}
});
if (valid) {
var dateStart = [];
var dateEnd = [];
$.each($('.datepicker'), function() {
if ($(this).hasClass('startDate')) dateStart.push($(this).val())
else dateEnd.push($(this).val())
});
$.each($(dateStart), function(key, value) {
var x = dateStart[key].split("-");
var y = dateEnd[key].split("-");
var failed = false;
var fromdate = new Date(x[2], x[0] - 1, x[1]);
var todate = new Date(y[2], y[0] - 1, y[1]);
var locDiffDays = parseInt((todate.getTime() - fromdate.getTime()) / (1000 * 60 * 60 * 24));
if (locDiffDays < 0) {
alert("To date " + dateEnd[key] + " should be greater then from date " + dateStart[key]);
console.log("invalid from and to dates");
failed = true;
return false;
}
if (dateStart[key - 1]) {
var x1 = dateStart[key - 1].split("-");
var y1 = dateEnd[key - 1].split("-");
var fromdate1 = new Date(x1[2], x1[0] - 1, x1[1]);
var todate1 = new Date(y1[2], y1[0] - 1, y1[1]);
var locDiffDays1 = parseInt((todate1.getTime() - fromdate1.getTime()) / (1000 * 60 * 60 * 24));
var locDiffDays2 = parseInt((fromdate.getTime() - fromdate1.getTime()) / (1000 * 60 * 60 * 24));
var locDiffDays3 = parseInt((todate.getTime() - todate1.getTime()) / (1000 * 60 * 60 * 24));
var locDiffDays4 = parseInt((fromdate.getTime() - todate1.getTime()) / (1000 * 60 * 60 * 24));
console.log("locDiffDays2: " + locDiffDays2);
if (locDiffDays2 < 0) {
alert("From date " + dateStart[key] + " should be greater than previous from date " + dateStart[key - 1]);
console.log("invalid from dates");
failed = true;
return false;
}
if (locDiffDays3 < 0) {
alert("To date " + dateStart[key] + " should be greater than previous To date " + dateStart[key - 1]);
console.log("invalid from dates");
failed = true;
return false;
}
if (locDiffDays4 < 0) {
alert("From date " + dateStart[key] + " should be greater than previous To date " + dateEnd[key - 1]);
console.log("invalid from dates");
failed = true;
return false;
}
}
if (key == dateStart.length - 1 && !failed) {
var firstDate = dateStart[0].split('-');
firstDate = new Date(firstDate[2], firstDate[0] - 1, firstDate[1]);
var lastDate = dateEnd[dateEnd.length - 1].split('-');
lastDate = new Date(lastDate[2], lastDate[0] - 1, lastDate[1]);
console.log(lastDate);
console.log(firstDate);
//var diffYears = (lastDate.getTime() - firstDate.getTime()) / (1000 * 60 * 60 * 24 * 365);
var diffMonths = monthDiff(firstDate, lastDate);
//diffYears = parseInt(''+diffYears);
var diffYears = diffMonths / 12;
diffYears = parseInt('' + diffYears);
diffMonths = diffMonths - (diffYears * 12)
document.getElementById("txt_expy").innerHTML = diffYears + " years";
document.getElementById("txt_expm").innerHTML = diffMonths + " Months";
}
});
}
}
I have two HTML input boxes, that need to calculate the time difference in JavaScript onBlur (since I need it in real time) and insert the result to new input box.
Format example: 10:00 & 12:30 need to give me: 02:30
Thanks!
Here is one possible solution:
function diff(start, end) {
start = start.split(":");
end = end.split(":");
var startDate = new Date(0, 0, 0, start[0], start[1], 0);
var endDate = new Date(0, 0, 0, end[0], end[1], 0);
var diff = endDate.getTime() - startDate.getTime();
var hours = Math.floor(diff / 1000 / 60 / 60);
diff -= hours * 1000 * 60 * 60;
var minutes = Math.floor(diff / 1000 / 60);
// If using time pickers with 24 hours format, add the below line get exact hours
if (hours < 0)
hours = hours + 24;
return (hours <= 9 ? "0" : "") + hours + ":" + (minutes <= 9 ? "0" : "") + minutes;
}
DEMO: http://jsfiddle.net/KQQqp/
Try This
var dif = ( new Date("1970-1-1 " + end-time) - new Date("1970-1-1 " + start-time) ) / 1000 / 60 / 60;
tl;dr
One off run
const t1 = new Date(1579876543210) // your initial time
const t2 = new Date(1579987654321) // your later time
const diff = t2-t1
const SEC = 1000, MIN = 60 * SEC, HRS = 60 * MIN
const humanDiff = `${Math.floor(diff/HRS)}:${Math.floor((diff%HRS)/MIN).toLocaleString('en-US', {minimumIntegerDigits: 2})}:${Math.floor((diff%MIN)/SEC).toLocaleString('en-US', {minimumIntegerDigits: 2})}.${Math.floor(diff % SEC).toLocaleString('en-US', {minimumIntegerDigits: 4, useGrouping: false})}`
console.log("humanDiff:", humanDiff)
// > humanDiff: 30:51:51.0111
As a function
function humanDiff (t1, t2) {
const diff = Math.max(t1,t2) - Math.min(t1,t2)
const SEC = 1000, MIN = 60 * SEC, HRS = 60 * MIN
const hrs = Math.floor(diff/HRS)
const min = Math.floor((diff%HRS)/MIN).toLocaleString('en-US', {minimumIntegerDigits: 2})
const sec = Math.floor((diff%MIN)/SEC).toLocaleString('en-US', {minimumIntegerDigits: 2})
const ms = Math.floor(diff % SEC).toLocaleString('en-US', {minimumIntegerDigits: 4, useGrouping: false})
return `${hrs}:${min}:${sec}.${ms}`
}
const t1 = new Date(1579876543210)
const t2 = new Date(1579987654321)
console.log("humanDiff(t1, t2):", humanDiff(t1, t2))
// > humanDiff: 30:51:51.0111
Explanation
Adjust humanDiff for your maximum and minimum reportable increments and formatting needs:
const t1 = new Date(1579876543210) // Set your initial time (`t1`)
const t2 = new Date(1579986654321) // , conclusion time (`t2`), and
const diff = t2-t1 // calculate their difference in milliseconds
console.log(" t2:", t2.toISOString()) // > t2: 2020-01-25T21:27:34.321Z
console.log(" t1:", t1.toISOString()) // > t1: 2020-01-24T14:35:43.210Z
console.log(" diff:", diff) // > diff: 111111111
// Set your constant time values for easy readability
const SEC = 1000
const MIN = 60 * SEC
const HRS = 60 * MIN
/* For a given unit
1) disregard any previously relevant units, e.g. to calculate minutes, we can
disregard all hours & focus on only the remainder - `(diff%HRS)`
2) divide the remainder by the given unit, e.g. for minutes, `(diff%HRS)/MIN`
3) disregard any remainder, e.g. again for minutes, `Math.floor((diff%HRS)/MIN)`
NOTE: for your maximum unit (HRS in the examples below) you probably _don't_
want to disregard high values, e.g. If the difference is >24 hrs and something,
you should either include a DAYS value, or simply display 30 hrs */
let hrs = Math.floor(diff/HRS)
let min = Math.floor((diff%HRS)/MIN)
let sec = Math.floor((diff%MIN)/SEC)
let ms = Math.floor(diff % SEC) // just the remainder
// BUT ms IS NOT ACTUALLY CORRECT, see humanDiff_3 for the fix ;-)
let humanDiff_1 = `${hrs}:${min}:${sec}.${ms}`
console.log("humanDiff_1:", humanDiff_1)
// > humanDiff_1: 30:51:51.111
sec = Math.round((diff%MIN)/SEC) // can also just round the last unit
const humanDiff_2 = `${hrs} hrs ${min} mins & ${sec} secs`
console.log("humanDiff_2:", humanDiff_2)
// > humanDiff_2: 30 hrs 51 mins & 51 secs
/* To ensure a set number of digits, format the numbers with `toLocaleString`'s
`minimumIntegerDigits`, if more than 3 digits, also use its `useGrouping` */
hrs = Math.floor(diff/HRS)
min = Math.floor((diff%HRS)/MIN).toLocaleString('en-US', {minimumIntegerDigits: 2})
sec = Math.floor((diff%MIN)/SEC).toLocaleString('en-US', {minimumIntegerDigits: 2})
ms = Math.floor(diff % SEC).toLocaleString('en-US', {minimumIntegerDigits: 4, useGrouping: false})
const humanDiff_3 = `${hrs}:${min}:${sec}.${ms}`
console.log("humanDiff_3:", humanDiff_3)
// > humanDiff_3: 30:51:51.0111
// NOTE: milliseconds are now 4 digits
This solution works for calculating diff between to separate military times
Example format: start = 23:00 / end = 02:30
function diff(start, end) {
start = start.split(":");
end = end.split(":");
if(Number(start[0]) > Number(end[0]) ) {
var num = Number(start[0])
var countTo = Number(end[0]);
var count = 0;
for (var i = 1; num != countTo;) {
num = num + i
if(num > 24) {
num = 0
}
count++
}
var hours = count - 1;
var startDate = new Date(0, 0, 0, start[0], start[1], 0);
var endDate = new Date(0, 0, 0, end[0], end[1], 0);
if(startDate.getMinutes() > endDate.getMinutes()) {
var hours = count - 2;
var diff = 60 - (startDate.getMinutes() - endDate.getMinutes());
} else {
var diff = endDate.getMinutes() - startDate.getMinutes();
}
var minutes = diff
} else {
var startDate = new Date(0, 0, 0, start[0], start[1], 0);
var endDate = new Date(0, 0, 0, end[0], end[1], 0);
var diff = endDate.getTime() - startDate.getTime();
var hours = Math.floor(diff / 1000 / 60 / 60);
diff -= hours * 1000 * 60 * 60;
var minutes = Math.floor(diff / 1000 / 60);
}
var returnValue = (hours < 9 ? "0" : "") + hours + ":" + (minutes < 9 ? "0" : "") + minutes
return returnValue;
}
Well this work almost great. Now use this code to calculate: 23:50 - 00:10 And see what you get.Or even 23:30 - 01:30. That's a mess.
Because getting the answer the other way in php is:
$date1 = strtotime($_POST['started']);
$date2 = strtotime($_POST['ended']);
$interval = $date2 - $date1;
$playedtime = $interval / 60;
But still, it works like yours.
I guess have to bring in the dates aswell?
And again: My hard research and development helped me.
if (isset($_POST['calculate'])) {
$d1 = $_POST['started'];
$d2 = $_POST['ended'];
if ($d2 < $d1) {
$date22 = date('Y-m-');
$date222 = date('d')-1;
$date2 = $date22."".$date222;
} else {
$date2 = date('Y-m-d');
}
$date1 = date('Y-m-d');
$start_time = strtotime($date2.' '.$d1);
$end_time = strtotime($date1.' '.$d2); // or use date('Y-m-d H:i:s') for current time
$playedtime = round(abs($start_time - $end_time) / 60,2);
}
And that's how you calculate time over to the next day.
//edit. First i had date1 jnd date2 switched. I need to -1 because this calculation only comes on next day and the first date vas yesterday.
After improving and a lot of brain power with my friend we came up to this:
$begin=mktime(substr($_GET["start"], 0,2),substr($_GET["start"], 2,2),0,1,2,2003);
$end=mktime(substr($_GET["end"], 0,2),substr($_GET["end"], 2,2),0,1,3,2003);
$outcome=($end-$begin)-date("Z");
$minutes=date("i",$outcome)+date("H",$outcome)*60; //Echo minutes only
$hours = date("H:i", $outcome); //Echo time in hours + minutes like 01:10 or something.
So you actually need only 4 lines of code to get your result. You can take only minutes or show full time (like difference is 02:32) 2 hours and 32 minutes.
What's most important: Still you can calculate overnight in 24 hour clock aka: Start time 11:50PM to let's say 01:00 AM (in 24 hour clock 23:50 - 01:00) because in 12 hour mode it works anyway.
What's most important: You don't have to format your input. You can use just plain 2300 as 23:00 input. This script will convert text field input to correct format by itself.
Last script uses standard html form with method="get" but you can convert it to use POST method as well.
This is an updated version of one that was already submitted. It is with the seconds.
function diff(start, end) {
start = start.split(":");
end = end.split(":");
var startDate = new Date(0, 0, 0, start[0], start[1], 0);
var endDate = new Date(0, 0, 0, end[0], end[1], 0);
var diff = endDate.getTime() - startDate.getTime();
var hours = Math.floor(diff / 1000 / 60 / 60);
diff -= hours * (1000 * 60 * 60);
var minutes = Math.floor(diff / 1000 / 60);
diff -= minutes * (1000 * 60);
var seconds = Math.floor(diff / 1000);
// If using time pickers with 24 hours format, add the below line get exact hours
if (hours < 0)
hours = hours + 24;
return (hours <= 9 ? "0" : "") + hours + ":" + (minutes <= 9 ? "0" : "") + minutes + (seconds<= 9 ? "0" : "") + seconds;
}
My Updated Version:
Allows for you to convert the dates into milliseconds and go off of that instead of splitting.
Example Does -- Years/Months/Weeks/Days/Hours/Minutes/Seconds
Example: https://jsfiddle.net/jff7ncyk/308/
With seconds you provided is not get result to me please find my updated function giving you the correct seconds here - By Dinesh J
function diff(start, end) {
start = start.split(":");
end = end.split(":");
var startDate = new Date(0, 0, 0, start[0], start[1],start[2], 0);
var endDate = new Date(0, 0, 0, end[0], end[1],end[2], 0);
var diff = endDate.getTime() - startDate.getTime();
var hours = Math.floor(diff / 1000 / 60 / 60);
diff -= hours * 1000 * 60 * 60;
var minutes = Math.floor(diff / 1000 / 60);
var seconds = Math.floor(diff / 1000)-120;
// If using time pickers with 24 hours format, add the below line get exact hours
if (hours < 0)
hours = hours + 24;
return (hours <= 9 ? "0" : "") + hours + ":" + (minutes <= 9 ? "0" : "") + minutes+ ":" + (seconds <= 9 ? "0" : "") + seconds;
}
Depending on what you allow to enter, this one will work. There may be some boundary issues if you want to allow 1am to 1pm
NOTE: This is NOT using a date objects or moment.js
function pad(num) {
return ("0"+num).slice(-2);
}
function diffTime(start,end) {
var s = start.split(":"), sMin = +s[1] + s[0]*60,
e = end.split(":"), eMin = +e[1] + e[0]*60,
diff = eMin-sMin;
if (diff<0) { sMin-=12*60; diff = eMin-sMin }
var h = Math.floor(diff / 60),
m = diff % 60;
return "" + pad(h) + ":" + pad(m);
}
document.getElementById('button').onclick=function() {
document.getElementById('delay').value=diffTime(
document.getElementById('timeOfCall').value,
document.getElementById('timeOfResponse').value
);
}
<input type="time" id="timeOfCall">
<input type="time" id="timeOfResponse">
<button type="button" id="button">CLICK</button>
<input type="time" id="delay">
calTimeDifference(){
this.start = dailyattendance.InTime.split(":");
this.end = dailyattendance.OutTime.split(":");
var time1 = ((parseInt(this.start[0]) * 60) + parseInt(this.start[1]))
var time2 = ((parseInt(this.end[0]) * 60) + parseInt(this.end[1]));
var time3 = ((time2 - time1) / 60);
var timeHr = parseInt(""+time3);
var timeMin = ((time2 - time1) % 60);
}
TimeCount = function()
{
t++;
var ms = t;
if (ms == 99)
{
s++;
t = 0;
if ( s == 60)
{
m++;
s = 0;
}
}
Dis_ms = checkTime(ms);
Dis_s = checkTime(s);
Dis_m = checkTime(m);
document.getElementById("time_val").innerHTML = Dis_m + ":" + Dis_s+ ":" + Dis_ms;
}
function checkTime(i)
{
if (i<10) {
i = "0" + i;
}
return i;
}
Try this: actually this a problem from codeeval.com
I solved it in this way .
This program takes a file as the argument so i used a little node js to read the file.
Here is my code.
var fs = require("fs");
fs.readFileSync(process.argv[2]).toString().split('\n').forEach(function (line) {
if (line !== "") {
var arr = line.split(" ");
var arr1 = arr[0].split(":");
var arr2 = arr[1].split(":");
var time1 = parseInt(arr1[0])*3600 + parseInt(arr1[1])*60 + parseInt(arr1[2]);
var time2 = parseInt(arr2[0])*3600 + parseInt(arr2[1])*60 + parseInt(arr2[2]);
var dif = Math.max(time1,time2) - Math.min(time1,time2);
var ans = [];
ans[0] = Math.floor(dif/3600);
if(ans[0]<10){ans[0] = "0"+ans[0]}
dif = dif%3600;
ans[1] = Math.floor(dif/60);
if(ans[1]<10){ans[1] = "0"+ans[1]}
ans[2] = dif%60;
if(ans[2]<10){ans[2] = "0"+ans[2]}
console.log(ans.join(":"));
}
});
We generally need time difference to estimate time taken by I/O operations, SP call etc, the simplest solution for NodeJs (the console is in callback- async execution) is following:
var startTime = new Date().getTime();
//This will give you current time in milliseconds since 1970-01-01
callYourExpectedFunction(param1, param2, function(err, result){
var endTime = new Date().getTime();
//This will give you current time in milliseconds since 1970-01-01
console.log(endTime - startTime)
//This will give you time taken in milliseconds by your function
if(err){
}
else{
}
})