need to find the difference between timings without dates in javascript application - javascript

In javascript application, I don't have Dates but only timings of a day in 24hrs format. How can I properly find the difference between them?
All my google search results are giving Date Time difference calculations only.
For example, If I want to find the difference between (4.15pm to 2.45 pm),
In my code I have,
var startTime = "14.45"; var endTime = "16.15";
Now var diffTime = endTime - startTime, which should give 1.30.
To get clarity on my question, you can refer my related question SO, to understand what I am trying to achieve.

Convert your string into the smallest unit required, which is minutes in your case. Do the arithmetic to get the result in minutes. Again do arithmetic to find hours and minutes from the result. You can also add logic to check if hours is zero and change to 24 in that case. But as comments point out, bare times cannot be compared if not of the same date.
function getMinutes(timeString){
var hours = parseInt(timeString.split('.')[0], 10);
hours = hours === 0? 24 : hours;
var minutes = parseInt(timeString.split('.')[1], 10);
var totalMinutes = (hours * 60) + minutes;
return totalMinutes;
}
var startTime = "23.45";
var endTime = "0.15";
var differenceInMinutes = getMinutes(endTime) - getMinutes(startTime);
var resultString = Math.floor(differenceInMinutes/60) + "." + (differenceInMinutes%60);
Another way can be by creating dummy dates using date constructor and keeping date part as some arbitrary date (same for end and start) and do common date comparison methods.

You seem to have 2 string variables in javascript. So talking about times and dates is really too early. They pretty much look like floating point numbers but if this was the case then the only arithmetic you could apply to floating point numbers is floating point arithmetic (+, -, *, /). So the first step for you would be to parse those string variables to the corresponding floating point numbers:
var startTime = '14.45';
var endTime = '16.15';
var startTimeFloat = parseFloat(startTime);
var endTimeFloat = parseFloat(endTime);
if (isNaN(startTimeFloat) || isNaN(endTimeFloat)) {
alert('Please input valid floating point numbers before being able to do any arithmetic on them');
} else {
var difference = endTimeFloat - startTimeFloat;
// Obviously here you should take into account the case where
// the start number is bigger than the end number in which case
// you would get a negative value for the difference. If you care only
// about the absolute value of the difference then you may use the
// Math.abs javascript method. Just like that:
// var difference = Math.abs(endTimeFloat - startTimeFloat);
alert(difference);
}

Related

Extract hour and minute from date function

I want to pass the time variable extracted from the database as a Date function in jQuery and want to extract hours and minutes from it and want to store it in a javascript variable.
var time="<?php echo $row['time']; ?>";
var time=new Date(time);
var hrs=time.getHours();
var min=time.getMinutes();
Please find if there is any error in this code.
Without more knowledge I can't really give you an answer.
But its likely that you're expecting a Date Object, when in reality your DB is returning something else.
(Maybe a string?, a number?)
Make sure what type of data is exactly storen in your "time" variable. Would be my suggestion because I dont see errors in the code. Must be the logic
Really hope this helped but more insight into what your DB is doing would help getting a clear answer :)
Good Luck !
You could find answers for this all over Stackoverflow or read the docs on the date object.
However, here is an answer you might like
var myMinutes = 1; // This represent 1 minute subtraction
var myHours = 60; // This represent 60 minutes subtraction which is 1 hour
var dateMSubObject= new Date(oldDateObject.getTime() - myMinutes*60000); //Substracting your minutes variable
var dateHSubObject= new Date(oldDateObject.getTime() - myHours*60000); //Substracting your hours variable
To make it more managable you could do hours like this aswell for etc 24 hours
var myHours = 60*24; // This represent 24 hours subtraction
You could also make the above code a function which wil take paramters like units, type and from that return your desired result
The 60000 part is milliseconds and represents 1 minute.
And welcome to StackOverflow, if you take some time exploring the website you will quickly be able to find the most common questions usually followed by great answers :)
This did it for me:
let jsdate = new Date(unixtimestamp+1000);
example in use:
let a = new Date();
console.log("a ="+a)
let stamp = a.getTime()
console.log("stamp ="+stamp) // timestamp
let newTimeObj = new Date(stamp*1000)
console.log("newTimeObj :::::::"+newTimeObj)
OUTPUT::::
You need to convert the UNIX Timestamp(in seconds) which is coming from your PHP code to milliseconds, and then pass it as a parameter to a Date object.
Consider the below example in JavaScript:
//UNIX Timestamp from your PHP code
let timeInUNIXTimeStamp = "1581653281";
// Create a new JavaScript Date object based on the timestamp
// Multiplied by 1000 to convert it into milliseconds, from seconds, as Date object works in milliseconds
var date = new Date(timeInUNIXTimeStamp * 1000);
// Get Hours part from the timestamp
var hours = date.getHours();
// Get Minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// Will display time in H:M format
var timeInHMSFormat = hours + ':' + minutes.substr(-2);
console.log(timeInHMSFormat);
You can same achieve in PHP also, there you need to convert UNIX Timestamp to H:M format, using the date() function, where the first parameter will the format you wanted and the second will be your UNIX Timestamp.
Example: date("h:i", 1581653281);
Where h is hours, in 12-hours format
i is minutes
Read move about PHP's data() function Date function in php
Consider PHP the code below, inside your JavaScript:
var time="<?php echo date('h:i', $row['time']); ?>";
//Now Split the above string into array
var timeArray = time.split(":");
var hours = timeArray[0];
var minutes = timeArray[1];
For more detail see this answer Convert UNIX Timestamp

Timesheet hours difference in moment.js

I have a string '08:30-16:30' describing working hours.
I also have the time someone has worked, in HH:mm format,eg.09:15
What is the easiest-fastest way to convert them in dates and find the difference in HH:mm format ?
Should i use Moment.js?
Also,i need the difference in minutes or seconds so that i can do comparisons with that.
I would be grateful if you could give me some examples.
For finding the difference between the working hours, you could make use of MomentJS.
Example:
var working_hours = '08:30-16:30';
var hours_arr = working_hours.split('-'); // Gives an array with ['08:30', '16:30']
var start = moment(hours_arr[0], "HH:mm");
var end = moment(hours_arr[1], "HH:mm");
var duration = moment.duration(end.diff(start));
var minutes = parseInt(duration.asMinutes());
The minutes variable would contain the difference in minutes.

Minutes since midnight in Momentjs

In pure JS, this would be how.
How can I find out the number of minutes since midnight for a given moment object (without extracting to Date)?
Must take into account DSTs
Minutes should be rounded
Must work with local time (not convert to UTC)
// Your moment
var mmt = moment();
// Your moment at midnight
var mmtMidnight = mmt.clone().startOf('day');
// Difference in minutes
var diffMinutes = mmt.diff(mmtMidnight, 'minutes');
By default, moment#diff will return number rounded down. If you want the floating point number, pass true as the third argument. Before 2.0.0, moment#diff returned rounded number, not a rounded down number.
Consider this pseudocode because I haven't test to see if the difference takes into account DST.
This is what I have at the moment:
if (!moment.isMoment(mmt)) {
return 0;
}
var hh = mmt.get('hour');
var mm = mmt.get('minute');
return hh*60 + mm;
I am not sure if it takes into account various edge cases; comment if this is the case, or provide an alternate answer.

how to calculate number of days between today and given date and code for getTime()?

I want to calculate number of days between today and a given date and check whether how many days remaining until today or how many days past from today.
var today = new Date();
var date_to_reply = new Date('2012-10-15');
var timeinmilisec = today.getTime() - date_to_reply.getTime();
console.log( Math.floor(timeinmilisec / (1000 * 60 * 60 * 24)) );
this gives me 5 as answer but how should i get (-5) since the date_to_reply is 5days past from today?
is this the correct way to calculate any given date?
Regards
What you are doing is correct: You want to calculate the difference (as number of days) between two dates. A difference can't be smaller than zero.
Although your date_to_reply is already in the past, theres still a 5 day difference.
So, everythings fine - it's the correct way.
EDIT:
If you want a negative value as result, try this:
var today = new Date();
var date_to_reply = new Date('2012-10-15');
var timeinmilisec = date_to_reply.getTime() - today.getTime();
console.log( Math.ceil(timeinmilisec / (1000 * 60 * 60 * 24)) );
Remember you need to Math.ceil the final result instead of rounding it down with Math.floor().
If you want the value to be negative (indicating date_to_reply is in the past) you should subtract the past date from the current: date_to_reply.getTime() - today.getTime().
Check this link for ways to calculate more diffentiated results.
If you swap the order of the dates, you'll get the negative number you want.
Better yet you could write a function that does this.
It could subtract the first parameter from the second.
The second parameter could default to today.
function diffDates(dateOne, dateTwo) {
if (typeof dateTwo === 'undefined') {
dateTwo = new Date();
}
return dateOne.getTime() - dateTwo.getTime();
}
It would be better to have the function operate on numbers rather than dates.
That would be more flexible, but I'm typing on an iPad right now!
Its obvious because today's date is greater than the previous. So either you need to make it negative on your own or use this
var timeinmilisec = date_to_reply.getTime()-today.getTime();

How to perform date subtraction in javascript

It's a little complicated to calculate delta time in js.
this is the pseudo-code,
var atime = "2010-12-05T08:03:22Z";
var btime = "2010-01-11T08:01:57Z"
var delta_time = btime - atime;
delta_time ?
I want to know exact date time between two time inputs.
is there any easy way to find out delta time?
var atime = new Date("2010-12-05T08:03:22Z");
var btime = new Date("2010-01-11T08:01:57Z");
var delta_time = btime - atime;
The value of delta_time will be the difference between the two dates in milliseconds.
If you're only interested in the difference, and don't care to differentiate between which is the later date, you might want to do
var delta_time = Math.abs(btime - atime);
A Date / Time object displays a time in a current situation (e.g. now() ). Displaying a difference of time is not part of a Date or Time object because the difference between e.g. May 1 and May 3 would result in, maybe, January 3, 1970, or maybe May 2, depends on how you start counting your delta on.
I would suggest putting your times into a timestamp which is a simple int in seconds. Do some substraction and voilá, there's your delta seconds. This delta can be used to apply to any other Object.

Categories

Resources