how to check the diffrence between dates - javascript

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

Related

Time calculation with milliseconds in JS

I want to find difference between two time with milliseconds value in Javascript.
As you can see below snapshot, where I calculated two time values in Excel.
My expectation exactly same calculated value with JS code.
I tried some code snippet but I got slightly difference in seconds.
var d1 = '2020-12-15 01:00:23.788';
var d2 = '2020-12-15 01:00:55.482';
var date1 = new Date(d1);
var date2 = new Date(d2);
//date2 += 500;
//date2 = new Date(date2);
//date2.setMilliseconds(5);
var date1_ms = date1.getTime();
var date2_ms = date2.getTime();
// Calculate the difference in milliseconds
var difference_ms = date2_ms - date1_ms;
//take out milliseconds
difference_ms = difference_ms / 1000;
var seconds = Math.floor(difference_ms % 60);
difference_ms = difference_ms / 60;
var minutes = Math.floor(difference_ms % 60);
difference_ms = difference_ms / 60;
var hours = Math.floor(difference_ms % 24);
var demo = hours + ' hours, ' + minutes + ' minutes, and ' + seconds + ' seconds.' + difference_ms;
document.getElementById("demo").innerHTML = demo;
<h2>JavaScript new Date()</h2>
<p>new Date() creates a new date object with the current date and time:</p>
<p id="demo"></p>
OUTPUT:
new Date() creates a new date object with the current date and time:
0 hours, 0 minutes, and 31 seconds.0.008803888888888889
JS does the same when correctly implemented
I tried with more interesting times
// Excel: 02:10:55,482 - 01:09:23,788 = 01:01:31,694
const fmtTime = date => {
const hours = `0${date.getHours() - 1}`.slice(-2);
const minutes = `0${date.getMinutes()}`.slice(-2);
const seconds = `0${date.getSeconds()}`.slice(-2);
const ms = `00${date.getMilliseconds()}`.slice(-3);
return `${hours}:${minutes}:${seconds}.${ms}`
}
const from = "01:09:23,788"
const to = "02:10:55.482"
const re = /(\d{2}):(\d{2}):(\d{2}).(\d{3})/;
const [m1, fromhh, frommm, fromss, fromms] = from.match(re);
const [m2, tohh, tomm, toss, tomms] = to.match(re);
// method one
let d = new Date()
d.setHours(fromhh, frommm, fromss, fromms)
const fromTime = d.getTime()
d.setHours(tohh, tomm, toss, tomms)
const toTime = d.getTime()
const diffInMS1 = toTime - fromTime
console.log(diffInMS1)
d = new Date(diffInMS1);
console.log(fmtTime(d))
// Method 2 - Note I need to cast to int where I only add (+fromms)
let fromMS = (fromhh * 60 * 60 * 1000) + (frommm * 60 * 1000) + (fromss * 1000) + +fromms;
let toMS = (tohh * 60 * 60 * 1000) + (tomm * 60 * 1000) + (toss * 1000) + +tomms;
const diffInMS2 = toMS - fromMS;
console.log(diffInMS2)
d = new Date(diffInMS2);
console.log(fmtTime(d))
function splitInNumberArray(str) {
return str
.replace(/(:|\.)/g, " ")
.split(" ")
.map((x) => parseInt(x));
}
function convertToMilliseconds(timeArray) {
return (
timeArray[0] * 60 * 60 * 1000 +
timeArray[1] * 60 * 1000 +
timeArray[2] * 1000 +
timeArray[3]
);
}
function msToTime(duration) {
var milliseconds = parseInt((duration % 1000) / 100),
seconds = Math.floor((duration / 1000) % 60),
minutes = Math.floor((duration / (1000 * 60)) % 60),
hours = Math.floor((duration / (1000 * 60 * 60)) % 24);
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
}
// This function is taken from https://stackoverflow.com/questions/19700283/how-to-convert-time-milliseconds-to-hours-min-sec-format-in-javascript
function parseDuration(duration) {
let remain = duration;
let hours = Math.floor(remain / (1000 * 60 * 60));
remain = remain % (1000 * 60 * 60);
let minutes = Math.floor(remain / (1000 * 60));
remain = remain % (1000 * 60);
let seconds = Math.floor(remain / 1000);
remain = remain % 1000;
let milliseconds = remain;
return {
hours,
minutes,
seconds,
milliseconds,
};
}
function minTwoDigits(n) {
return (n < 10 ? "0" : "") + n;
}
//***************************************
const time1 = "01:00:55.482";
const time2 = "01:00:23.788";
const numberArray1 = splitInNumberArray(time1);
const numberArray2 = splitInNumberArray(time2);
const msTime1 = convertToMilliseconds(numberArray1);
const msTime2 = convertToMilliseconds(numberArray2);
const diff = msTime1 - msTime2;
const { hours, minutes, seconds, milliseconds } = parseDuration(diff);
console.log(
`${time1} - ${time2} = ${minTwoDigits(hours)}:${minTwoDigits(
minutes
)}:${minTwoDigits(seconds)}.${milliseconds}`
);

javascript - get the date of next day in week?

how do I get, for example, the date of next monday and the time 5:30PM, and calculate the difference between current date and time and that date and time?
if I run it now at 8/28/2020 17:35, it should give me 8/31/2020 17:30 and the difference 2 days 23 hours 55 minutes.
I hope this help:
// takes dayIndex from Sunday(0) to Saturday(6)
const getNextDay = (dayIndex) => {
const today = new Date();
today.setDate(
today.getDate() + ((dayIndex - 1 - today.getDay() + 7) % 7) + 1
);
today.setHours(17, 30, 00);
return today;
};
const getTimeleft = (dateNow, dateFuture) => {
let seconds = Math.floor((dateFuture - dateNow) / 1000);
let minutes = Math.floor(seconds / 60);
let hours = Math.floor(minutes / 60);
let days = Math.floor(hours / 24);
hours = hours - days * 24;
minutes = minutes - days * 24 * 60 - hours * 60;
seconds = seconds - days * 24 * 60 * 60 - hours * 60 * 60 - minutes * 60;
return `${days} days ${hours} hours ${minutes} minutes`;
};
const now = new Date();
const nextMonday = getNextDay(1);
const timeleft = getTimeleft(now, nextMonday);
console.log(nextMonday.toLocaleString());
console.log(timeleft);
You could use moment.js, it's a very useful library when it comes to dates:
<script src="https://momentjs.com/downloads/moment.js"></script>
<script>
const today = moment();
const nextMonday = moment().add(1, 'weeks').isoWeekday(1);
nextMonday.set({'hour': 17, 'minute': 30, 'seconds': 0});
console.log(nextMonday.toString());
const duration = moment.duration(nextMonday.diff(today));
const days = duration.asDays();
const hours = (days - Math.floor(days)) * 24;
const minutes = (hours - Math.floor(hours)) * 60;
console.log("days", Math.floor(days));
console.log("hours", Math.floor(hours));
console.log("minutes", Math.floor(minutes));
</script>
Here is the working example:
function nextWeekMonday(date)
{
var diff = date.getDate() - date.getDay() + (date.getDay() === 0 ? -6 : 1);
var currWeekMonday = new Date(date.setDate(diff));
return new Date(currWeekMonday.getTime() + 7 * 24 * 60 * 60 * 1000);
}
function getDateDifference(current, future) {
// get total seconds between the times
var delta = Math.abs(future - current) / 1000;
// calculate (and subtract) whole days
var days = Math.floor(delta / 86400);
delta -= days * 86400;
// calculate (and subtract) whole hours
var hours = Math.floor(delta / 3600) % 24;
delta -= hours * 3600;
// calculate (and subtract) whole minutes
var minutes = Math.floor(delta / 60) % 60;
delta -= minutes * 60;
// what's left is seconds
var seconds = delta % 60;
return `${days} Days, ${hours} Hours, ${minutes} Minutes, ${seconds} Seconds`;
}
var curr = new Date; // get current date
var nextMonday = nextWeekMonday(curr);
console.log(getDateDifference(curr, nextMonday));

get time since date in year, month, days, hour, minute, and seconds

I am trying to get time from November 28, 2016 .
i want that time shows like it has been 1 year 2 month 6 days 17 hour 19 minute and 36 seconds.
var dateString = '11/28/2016';
var now = new Date();
var today = new Date(now.getYear(), now.getMonth(), now.getDate());
var yearNow = now.getYear();
var monthNow = now.getMonth();
var dateNow = now.getDate();
var dob = new Date(dateString.substring(6, 10),
dateString.substring(0, 2) - 1,
dateString.substring(3, 5)
);
var yearDob = dob.getYear();
var monthDob = dob.getMonth();
var dateDob = dob.getDate();
var time = {};
yearTime = yearNow - yearDob;
if (monthNow >= monthDob)
var monthTime = monthNow - monthDob;
else {
yearTime--;
var monthTime = 12 + monthNow - monthDob;
}
if (dateNow >= dateDob)
var dateTime = dateNow - dateDob;
else {
monthTime--;
var dateTime = 31 + dateNow - dateDob;
if (monthTime < 0) {
monthTime = 11;
yearTime--;
}
}
time = {
years: yearTime,
months: monthTime,
days: dateTime
};
if (time.months < 9) {
time.months = '0' + time.months;
}
if (time.days < 9) {
time.days = '0' + time.days;
}
$('#cnt_year').text('0' + time.years);
$('#cnt_month').text(now);
$('#cnt_days').text(time.days);
it shows Year, month and days but how do i add hours and minute.
Given there are only 30 days in a month/all monnths.
var dateString = '11/28/2016';
var now = new Date();
var today = new Date(now.getYear(), now.getMonth(), now.getDate());
var yearNow = now.getYear();
var monthNow = now.getMonth();
var dateNow = now.getDate();
var dob = new Date(dateString.substring(6, 10),
dateString.substring(0, 2) - 1,
dateString.substring(3, 5)
);
var nTotalDiff = Math.abs(now - dob);
var oDiff = {};
oDiff.years = Math.floor(nTotalDiff / 1000 / 60 / 60 / 24 / 30 / 12);
nTotalDiff -= oDiff.years * 1000 * 60 * 60 * 24 * 30 * 12;
oDiff.months = Math.floor(nTotalDiff / 1000 / 60 / 60 / 24 / 30);
nTotalDiff -= oDiff.months * 1000 * 60 * 60 * 24 * 30;
oDiff.days = Math.floor(nTotalDiff / 1000 / 60 / 60 / 24);
nTotalDiff -= oDiff.days * 1000 * 60 * 60 * 24;
oDiff.hours = Math.floor(nTotalDiff / 1000 / 60 / 60);
nTotalDiff -= oDiff.hours * 1000 * 60 * 60;
oDiff.minutes = Math.floor(nTotalDiff / 1000 / 60);
nTotalDiff -= oDiff.minutes * 1000 * 60;
oDiff.seconds = Math.floor(nTotalDiff / 1000);
console.log( oDiff );
Here's an example of how you can use moment.js's diff and add functionality,
const today = moment();
const dateString = moment('11/28/2016');
const diffYears = today.diff(dateString, 'years'); // diff gives you the difference between two days in integer.
dateString.add(diffYears, 'years'); // to get difference in month now, you first need to add `diffYears` to the dateString, same follows for the further calculations.
const diffMonths = today.diff(dateString, 'months');
dateString.add(diffMonths, 'months');
const diffDays = today.diff(dateString, 'days');
dateString.add(diffDays, 'days');
const diffHours = today.diff(dateString, 'hours');
dateString.add(diffHours, 'hours');
const diffMinutes = today.diff(dateString, 'minutes');
dateString.add(diffMinutes, 'minutes');
const diffSeconds = today.diff(dateString, 'seconds');
You can find more examples at http://momentjs.com/docs/#/displaying/difference/

How to reduce the cyclomatic complexity of this function?

I have a function that takes a timestamp in epoch (like 1517073001) and returns the time that has passed since then in a simple format like "2 hours ago" (not further verbosity like "2 hours, 31 minutes and 15 seconds ago").
The function works as intended but JSHint complains about using too many statements (30) and its cyclomatic complexity being too high (12). I was wondering what could be a way to improve these two aspects.
This is the function:
function msToTime(epoch) {
var previous = new Date(epoch * 1000);
var current = Math.floor(new Date().getTime());
var ms = current - previous;
var years = parseInt((ms / (1000 * 60 * 60 * 24 * 30 * 12)).toFixed(20), 10);
var months = parseInt((ms / (1000 * 60 * 60 * 24 * 30) % 12).toFixed(20), 10);
var days = parseInt((ms / (1000 * 60 * 60 * 24) % 30).toFixed(20), 10);
var hours = parseInt((ms / (1000 * 60 * 60) % 24).toFixed(20), 10);
var minutes = parseInt(ms / (1000 * 60) % 60, 10);
var seconds = parseInt(ms / 1000 % 60, 10);
var formatted = '';
if (years > 0) {
if (years > 1) {
formatted = years + ' years ago';
} else {
formatted = years + ' year ago';
}
} else if (months > 0) {
if (months > 1) {
formatted = months + ' months ago';
} else {
formatted = months + ' month ago';
}
} else if (days > 0) {
if (days > 1) {
formatted = days + ' days ago';
} else {
formatted = days + ' day ago';
}
} else if (hours > 0) {
if (hours > 1) {
formatted = hours + ' hours ago';
} else {
formatted = hours + ' hour ago';
}
} else if (minutes > 0) {
if (minutes > 1) {
formatted = minutes + ' minutes ago';
} else {
formatted = minutes + ' minute ago';
}
} else {
if (seconds > 1) {
formatted = seconds + ' seconds ago';
} else {
formatted = seconds + ' second ago';
}
}
return formatted;
}
var div = document.getElementById('time');
div.innerHTML = msToTime(1517073001);
<div id="time"></div>
Thank you in advance. :)
Another version optimized for divs and modules operations
function msToTime(epoch) {
var value = (Math.floor(new Date().getTime()) - new Date(epoch * 1000)) / 1000;
var time_factors = [['second', 60], ['minute', 60], ['hour', 24], ['day', 30], ['month', 12], ['year', NaN]];
for (factor of time_factors) {
if (value < factor[1] || isNaN(factor[1])) {
var t = Math.floor(value);
return t + ' ' + (t > 1 ? factor[0] + 's' : factor[0]) + ' ago';
}
value /= factor[1];
}
}
Replacing if...else if...else if... by switch (true) and putting the building of singular or plural to a function:
function msToTime(epoch) {
let previous = new Date(epoch * 1000);
let current = Math.floor(new Date().getTime());
let ms = current - previous;
let years = parseInt((ms / (1000 * 60 * 60 * 24 * 30 * 12)).toFixed(20), 10);
let months = parseInt((ms / (1000 * 60 * 60 * 24 * 30) % 12).toFixed(20), 10);
let days = parseInt((ms / (1000 * 60 * 60 * 24) % 30).toFixed(20), 10);
let hours = parseInt((ms / (1000 * 60 * 60) % 24).toFixed(20), 10);
let minutes = parseInt(ms / (1000 * 60) % 60, 10);
let seconds = parseInt(ms / 1000 % 60, 10);
let formatted = '';
function timeAgo(count, word) {
return `${count} ${(count === 1 ? word : word + 's')} ago`
}
switch (true) {
case years > 0:
formatted = timeAgo(years, 'year')
break
case months > 0:
formatted = timeAgo(months, 'month')
break
case days > 0:
formatted = timeAgo(days, 'day')
break
case hours > 0:
formatted = timeAgo(hours, 'hour')
break
case minutes > 0:
formatted = timeAgo(minutes, 'minute')
break
default:
formatted = timeAgo(seconds, 'second')
}
return formatted;
}
time.innerHTML = msToTime(1517073001);
<div id="time"></div>
Defining the date as array and iterating over it has decreased the Cyclomatic complexity number to 4(!), with only 12 statements.
function msToTime(epoch) {
var previous = new Date(epoch * 1000);
var current = Math.floor(new Date().getTime());
var ms = current - previous;
var formatted = '';
var completeDate = [
['year', parseInt((ms / (1000 * 60 * 60 * 24 * 30 * 12)).toFixed(20), 10)],
['month', parseInt((ms / (1000 * 60 * 60 * 24 * 30) % 12).toFixed(20), 10)],
['day', parseInt((ms / (1000 * 60 * 60 * 24) % 30).toFixed(20), 10)],
['hour', parseInt((ms / (1000 * 60 * 60) % 24).toFixed(20), 10)],
['minute', parseInt(ms / (1000 * 60) % 60, 10)],
['second', parseInt(ms / 1000 % 60, 10)]
];
for (var i = 0; i < completeDate.length; i++) {
var amount = completeDate[i][1];
if (amount > 0) {
var unit = completeDate[i][0];
formatted = amount + ' ' + (amount > 1 ? unit + 's' : unit) + ' ago';
break;
}
}
return formatted;
}
var div = document.getElementById('time');
div.innerHTML = msToTime(1517073001);
<div id="time"></div>
Thank you, #connexo, for the important advice!
function msToTime (epoch) {
var previous = new Date(epoch * 1000);
var current = Math.floor(new Date().getTime());
var ms = current - previous;
var years = parseInt((ms / (1000 * 60 * 60 * 24 * 30 * 12)).toFixed(20), 10);
var months = parseInt((ms / (1000 * 60 * 60 * 24 * 30) % 12).toFixed(20), 10);
var days = parseInt((ms / (1000 * 60 * 60 * 24) % 30).toFixed(20), 10);
var hours = parseInt((ms / (1000 * 60 * 60) % 24).toFixed(20), 10);
var minutes = parseInt(ms / (1000 * 60) % 60, 10);
var seconds = parseInt(ms / 1000 % 60, 10);
var formatted = '';
if (years > 0) {
formatted = years > 1 ? years + ' years ago' : years + ' year ago';
} else if (months > 0) {
formatted = months > 1 ? ' months ago' : ' month ago';
} else if (days > 0) {
formatted = days > 1 ? ' days ago' : ' day ago';
} else if (hours > 0) {
formatted = hours > 1 ? ' hours ago' : ' hour ago';
} else if (minutes > 0) {
formatted = minutes > 1 ? ' minutes ago' : ' minute ago';
} else {
formatted = seconds > 1 ? ' seconds ago' : ' second ago';
}
return formatted;
}
var div = document.getElementById('time');
div.innerHTML = msToTime(1417073002);
I have used JS ternary operator to shorten you code. Hope it helps.

Calculate Time Difference with JavaScript

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{
}
})

Categories

Resources