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

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.

Related

How do i check given duration times (00:20:40,1:20:40,00:00:10) is <20sec, >1hour and <10 seconds [duplicate]

This question already has answers here:
How can I convert a HH:mm:ss string to a JavaScript Date object?
(3 answers)
Closed 4 years ago.
I am having a field called Duration it contains time like 00:20:40.How do i check given duration times (00:20:40,1:20:40,00:00:10) is <20sec, >1hour and <10 seconds .I tried the following but didn't work.
var time = new Date('00:10:40');
time.getMinutes();
Output will look like:
The given time is <20 minute.Hence i need to check like this
if(<20 minutes){...}
You have to create Date Object with Date to use it.
var d = new Date("1970-01-01 20:18:02");
document.write(d.getMinutes());
You can do the following:
var time = "00:20:40".split(":");
var minutes = time[1];
The given string "00:20:40" is not a valid date string and cannot be passed to new Date() as an argument. In this case, you can use the above solution which will split the string and give you an array consisting of [hh, mm, ss] and you will be able to get the minutes at time[1].
I hope it helps.
function toSeconds (duration) {
const regex = /(\d+):(\d+):(\d+)/;
const matched = duration.match(regex);
const hours = parseInt(matched[1]);
const minutes = parseInt(matched[2]);
const seconds = parseInt(matched[3]);
return (hours * 60 * 60) + (minutes * 60) + seconds;
}
function toMinutes (duration) {
const seconds = toSeconds(duration);
return seconds / 60;
}
function toHours (duration) {
const minutes = toMinutes(duration);
return minutes / 60;
}
toSeconds('00:20:40') // 1240
toMinutes('00:20:40') // 20.666666666666668
toMinutes('01:20:40') // 80.66666666666667
toHours('01:20:40') // 1.3444444444444446

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.

subtracting military time in javascript [duplicate]

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

How can I count the days between two dates in javascript? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to calculate the number of days between two dates using javascript
I have those dates :
27/09/2011
29/10/2011
and I'd like to return the days between those dates (in the example, should be 33 days).
How can I do it on javascript (or jquery?)?
var daysBetween = (Date.parse(DATE1) - Date.parse(DATE2)) / (24 * 3600 * 1000);
function days_between(date1, date2) {
// The number of milliseconds in one day
var ONE_DAY = 1000 * 60 * 60 * 24
// Convert both dates to milliseconds
var date1_ms = date1.getTime()
var date2_ms = date2.getTime()
// Calculate the difference in milliseconds
var difference_ms = Math.abs(date1_ms - date2_ms)
// Convert back to days and return
return Math.round(difference_ms/ONE_DAY)
}
http://www.mcfedries.com/JavaScript/DaysBetween.asp
// split the date into days, months, years array
var x = "27/09/2011".split('/')
var y = "29/10/2011".split('/')
// create date objects using year, month, day
var a = new Date(x[2],x[1],x[0])
var b = new Date(y[2],y[1],y[0])
// calculate difference between dayes
var c = ( b - a )
// convert from milliseconds to days
// multiply milliseconds * seconds * minutes * hours
var d = c / (1000 * 60 * 60 * 24)
// show what you got
alert( d )
Note:
I find this method safer than Date.parse() as you explicitly specify the date format being input (by splitting into year, month, day in the beginning). This is important to avoid ambiguity when 03/04/2008 could be 3rd of April, 2008 or 4th of March, 2008 depending what country your dates are coming from.

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