subtracting military time in javascript [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
check time difference in javascript
calculate time difference in javascript
this is my block of code to pull times from a form input,
start = group.find('.startTime').val().replace(':',''), // like 0100
end = group.find('.endTime').val().replace(':',''), // like 0300
timeDiff = (end - start) < 0 ? (end - start + 2400) : (end - start),
timeDiff accounts for times passing midnight, so like if I try and subtract 2300 from 0100, and get -2200, it adds the 2400 to get the correct difference of 0200, or 2 hours.
my problem arises where i try to subtract some times like 2100 - 2030 (which should give me a half hour) but because its just a raw number i get the actual difference of 70. my question is how would I correctly subtract these? If i need to convert it to a date or time object what would be the proper way of doing so? I looked into the setTime method but that didn't sound like what i needed.
Thanks in advance.

Without Date objects (which seems OK for time-only values), you should convert the time to minutes or hours - always calculate with only one unit (and especially never mix them into one decimal number representing a sexagesimal one)!
function toTime(string) {
var m = string.match(/(\d{2}):({\d2})/);
return m && 60 * parseInt(m[1], 10) + parseInt(m[2], 10),
}
var start = toTime( group.find('.startTime').val() ),
end = toTime( group.find('.endTime').val() );
var timeDiff = Math.abs(end - start);
function fromTime(minutes) {
var m = minutes % 60,
h = (minutes - m) / 60;
return ("0"+h).substr(-2)+":"+("0"+m).substr(-2);
}

Related

How to calculate is more than one second/hour passed using milliseconds? [duplicate]

This question already has answers here:
Getting difference in seconds from two dates in JavaScript
(2 answers)
Closed 3 years ago.
I want to calculate the time difference between two dates which have different format to know if more than one hour/seconds has passed.
The first format is: 2019-07-02T16:21:00.1030000
The second one is: 1562160899773
I am using getMilliseconds() but I don't know if it's the better way.
for example
var isMoreOneSec = New Date(2019-07-02T16:21:00.1030000).getMilliseconds() - new Date(1562160899773).getMilliseconds() > 1000
getMilliseconds() will return the number of milliseconds in the current second, hence will always return from 0 to 999, the same way getHour() will return from 0 to 23 or getSeconds() from 0 to 59.
When you have two dates, to get the difference in milliseconds you have to use getTime() which will return the number of milliseconds sice unix epoch.
So:
var date1 = new Date("2019-07-02T16:21:00.1030000");
var date2 = new Date(1562160899773);
var date1time = date1.getTime();
var date2time = date2.getTime();
console.log("Date 1 time is", date1time);
console.log("Date 2 time is", date2time);
var dif = date2time - date1time;
console.log("Dif in ms is ", dif);
console.log("Is dif more than one second?", dif > 1000);
console.log("Is dif more than one hour?", dif > 60*60*1000);

Javascript/Moment - Issue with generating time slots

I am trying to generate time slots with a gap of 15min between each one, like the following :
["15:30", "15:45", "16:00", "16:15"...]
So far, I managed to make it. However, if the current time is 15:25 (just an example) the generated array will start from 15:30 what I need instead (in this case) to generate time slots starting from 16:00 meaning that only the first time slot should be approximately away 30 min from the current time.
Currently, I have the following code :
//Used momentJS library
function getTimeStops(end) {
var roundedUp, startTime, endTime, timeStops;
roundedUp = Math.ceil(moment().utc().minute() / 30) * 30;
startTime = moment().utc().set({
minute: roundedUp
});
endTime = moment(end, 'HH:mm');
if (endTime.isBefore(startTime)) {
endTime.add(1, 'day');
}
timeStops = [];
while (startTime <= endTime) {
timeStops.push(new moment(startTime).format('HH:mm'));
startTime.add(15, 'minutes');
}
return timeStops;
}
var timeStops = getTimeStops('02:00');
console.log('timeStops ', timeStops);
You're rounding to the nearest half hour here:
roundedUp = Math.ceil(moment().utc().minute() / 30) * 30;
Round to the nearest hour instead:
roundedUp = Math.ceil(moment().utc().minute() / 60) * 60;
Edit: just realised that the above is wrong and doesn't actually answer your question.
You do need to change your roundedUp value though.
What you need to do is:
Add 30 minutes to the current time
Round it to the closest 15 minute interval
That way - at most - you'll be 7.5 minutes out.
So for step 1, add 30 minutes
var add30mins = moment.utc().add(30, 'minutes')
Now we need to find the closest 15 minute interval.
var roundTo15Mins = Math.round(add30Mins.minute() / 15) * 15;
Then you can plug that into your startTime.
HTH

Is it possible to make a date validation in javascript? [duplicate]

This question already has answers here:
Get difference between 2 dates in JavaScript? [duplicate]
(5 answers)
Closed 8 years ago.
I have to check if two dates differ more than two days. As an example, 01/14/2014 and 01/15/2014 would fit the criteria because there's only one day of difference, but 01/14/2014 and 01/18/2014 would not as the latter has 4 days of difference. The dates are in string format so I've tried all sorts of data casting but couldn't succeed. So to sum up, i want to know if it is possible to create an if statement that subtract the value of two dates that are in string format and give a error if the value is bigger than 'n'. Thanks!
One solution would be to create a Javascript Date object (http://www.w3schools.com/js/js_obj_date.asp) for each date using simple string parsing, get the value in milliseconds using the .getTime() function and checking if this is greater than 1000 x 60 x 60 x 24 x 2 .
// https://gist.github.com/remino/1563878
// Converts millseconds to object with days, hours, minutes ans seconds.
function convertMS(ms) {
var d, h, m, s;
s = Math.floor(ms / 1000);
m = Math.floor(s / 60);
s = s % 60;
h = Math.floor(m / 60);
m = m % 60;
d = Math.floor(h / 24);
h = h % 24;
return { d: d, h: h, m: m, s: s };
};
var start_date = '04/15/2014';
var end_date = '04/16/2014';
var diff = convertMS(Date.parse(end_date) - Date.parse(start_date));
if(diff.d > 1) {
console.log('The difference is more than one day!');
}
else {
console.log('The difference is just one day and therefore accepted!');
}
See the js fiddle: http://jsfiddle.net/E7bCF/11/
See the js fiddle with more than a day difference: http://jsfiddle.net/E7bCF/9/
Try
new Date("MM/DD/YYYY") - new Date("MM/DD/YYYY")
That will return a number in milliseconds.

Javascript time difference via timepicker

I'm working on a web timesheet where users use timepicker to determine start & end times and I'd like to have the form automatically find the difference between the two times and place it in a 3rd input box. I understand that I need to get the values, convert them to milliseconds, then subtract the first number from the second, convert the difference back to human time and display that in the third box. But I can't seem to wrap my head around time conversion in javascript. Here's what I have so far:
function date1math(){
var date1in = document.getElementById("date-1-in").value;
var date1out = document.getElementById("date-1-out").value;
date1in = date1in.split(":");
date1out = date1out.split(":");
var date1inDate = new Date(0, 0, 0, date1in[0], date1in[1], 0);
var date1outDate = new Date(0, 0, 0, date1out[0], date1out[1], 0);
var date1math = date1outDate.getTime() - date1inDate.getTime();
var hours = Math.floor(date1math / 1000 / 60 / 60);
date1math -= hours * 1000 * 60 * 60;
var minutes = Math.floor(date1math / 1000 / 60);
return (hours < 9 ? "0" : "") + hours + ":" + (minutes < 9 ? "0" : "") + minutes;
document.getElementById("date-1-subtotal").value = date1math(date1in, date1out);
}
I want to take the timepicker result (say 9:00am) from the input date-1-in, the timepicker result (say 5:00pm) from the input date-1-out, and then place the difference as a number in date-1-subtotal.
Presumably the input is a string in the format hh:mm (e.g. 09:54) and that the two strings represent a time on the same day. You don't mention whether an am/pm suffix is included, but it's there in the text so I'll assume it might be.
If daylight saving changes can be ignored, the simplest method is to convert the string to minutes, find the difference, then convert back to hours and minutes, e.g.:
// Convert hh:mm[am/pm] to minutes
function timeStringToMins(s) {
s = s.split(':');
s[0] = /m$/i.test(s[1]) && s[0] == 12? 0 : s[0];
return s[0]*60 + parseInt(s[1]) + (/pm$/i.test(s[1])? 720 : 0);
}
// Return difference between two times in hh:mm[am/pm] format as hh:mm
function getTimeDifference(t0, t1) {
// Small helper function to padd single digits
function z(n){return (n<10?'0':'') + n;}
// Get difference in minutes
var diff = timeStringToMins(t1) - timeStringToMins(t0);
// Format difference as hh:mm and return
return z(diff/60 | 0) + ':' + z(diff % 60);
}
var t0 = '09:15am';
var t1 = '05:00pm';
console.log(getTimeDifference('09:15am', '05:00pm')); // 07:45
console.log(getTimeDifference('09:15', '17:00')); // 07:45
If daylight saving is to be incorporated, you'll need to include the date so that date objects can be created and used for the time difference. The above can use either 12 or 24 hr time format.

Javascript, how to find the difference between two datetimes in mysql timestamp style

Let's say I have
a = "2011-11-09 08:00:00"
b = "2011-11-10 08:30:00"
What's the best way of finding how many days, hours, minutes the difference between these two timestamps are in Javascript?
So the output should be "1 day" (ignore the minutes since there is a larger unit (day) in the difference) ?
The only reliable way to convert a string to a date in javascript is to parse it manually. If the format is consistent with what you have posted, then you can convert it to a date as follows:
function stringToDate(s) {
var dateParts = s.split(' ')[0].split('-');
var timeParts = s.split(' ')[1].split(':');
var d = new Date(dateParts[0], --dateParts[1], dateParts[2]);
d.setHours(timeParts[0], timeParts[1], timeParts[2])
return d
}
so you can do:
var a = "2011-11-09 08:00:00"
var b = "2011-11-10 08:30:00"
alert(stringToDate(a) - stringToDate(b));
to get the difference in milliseconds. However, the difference in days between two dates may not be a simple matter of dividing the difference by 8.64e7 (milliseconds in one da). You need to confirm the business logic in regard to that.
EDITED to work in any browser
var matchDate = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;
var firstDateParsed = matchDate.exec("2011-11-09 08:00:00");
var secondDateParsed = matchDate.exec("2011-11-10 08:30:00");
var a = new Date(firstDateParsed[1], firstDateParsed[2], firstDateParsed[3], firstDateParsed[4], firstDateParsed[5], firstDateParsed[6], 0);
var b = new Date(secondDateParsed[1], secondDateParsed[2], secondDateParsed[3], secondDateParsed[4], secondDateParsed[5], secondDateParsed[6], 0);
var differenceInMilliseconds = a.getTime() - b.getTime();
// minutes
alert(differenceInMilliseconds / 1000 / 60);
// hours
alert(differenceInMilliseconds / 1000 / 60 / 60);
// days
alert(differenceInMilliseconds / 1000 / 60 / 60 / 24);
Tested in IE and Firefox as well as Chrome: http://jsfiddle.net/xkBTS/4/
You'll have to parse the timestamp to a date yourself:
function parseMySQLTimestamp(timestamp) {
var parts = timestamp.match(/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/);
return new Date(+parts[1], (+parts[2] - 1), +parts[3], +parts[4], +parts[5], +parts[6]);
}
Get the difference in milliseconds by subtracting one date from the other:
var msDifference = parseMySQLTimestamp(b) - parseMySQLTimestamp(a);
Simple arithmetic will let you convert milliseconds to seconds, minutes, or whatever.
By the way, this function will throw an error if a timestamp is passed in that doesn't match the expression. From a software design point of view, this behavior makes sense to me. However, if you want to be able to use that function with strings that may not be in the correct format, you can just do a null check against parts and return null if there is no match.

Categories