I need some help with validating a date time string in Javascript, based on the browser's language.
I can get the datetime format easily enough, for instance if the language is set to pt-BR the format would be
dd/MM/yyyy HH:mm:ss
I tried using something like this:
var dateFormat = "dd/MM/yyyy HH:mm:ss";
var x = Date.parseExact($("#theDate").val(), dateFormat);
However x is always Null. I am thinking because Date.parseExact is not able to do times. I need to be able to do this for all browser languages and I would prefer to not use another library. Using Regex is out also since I would need to write so many different expressions.
Does anyone have any suggestions to help me ge on the right track? I am also not against using a webmethod.
I have tried using the following webmethod, which works with en-US but nothing else:
Public Function ValidateDates(ByVal strDate_In As String) As String
Dim theFormat As String = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern() + " " + CultureInfo.CurrentCulture.DateTimeFormat.LongTimePattern()
Try
Dim d As DateTime = DateTime.ParseExact(strDate_In, theFormat, CultureInfo.CurrentCulture)
Return "true"
Catch ex As Exception
Return "false"
End Try
End Function
You can use Regex to do this:
var dateFormat = "dd/MM/yyyy HH:mm:ss";
var x = $("#theDate").val().match(/^(\d{2})\/(\d{2})\/(\d{4}) (\d{2}):(\d{2}):(\d{2})$/);
console.log(x);
Demo: https://jsfiddle.net/kzzn6ac5/
update
The following regex may help you and improve it according to your need:
^((\d{2}|\d{4})[\/|\.|-](\d{2})[\/|\.|-](\d{4}|\d{2}) (\d{2}):(\d{2}):(\d{2}))$
It matches the following format with /.- and yyyy/mm/dd hh:mm:ss or dd/mm/yyyy hh:mm:ss
Updated demo: https://jsfiddle.net/kzzn6ac5/1 or https://regex101.com/r/aT1oL6/1
Further Regex expressions relevant to date matching can be found here.
JavaScript date objects are deceptively easy, I worked with them in a project and they had a sneaky learning-curve that takes a lot of time to master (as opposed to the rest of JavaScript, which is relative child's play). I recommend letting VB, or really anything else handle it.
But if you want a way to do it in javascript, without Regex (as stated in your question), you could perform string operations on it like this:
try {
var user_input = $("#theDate").val();
var split = user_input.split(" "); // 0: date, 1: time
var split_time = split[1].split(":"); // 0: hours, 1: minutes, 2: seconds
d.setHours(split_time[0]);
d.setMinutes(split_time[1]);
} catch {
// not in a valid format
}
This solution assumes the input is in the correct format, and if an error occurs, it's not. It's not the best way of doing things, but JS Date objects are seriously horrible.
Related
I'm kinda new to Javascript.
My problem is the following : I have to implement a form that is generated by a js file, by taking the url and paste it inside my HTML. I have a date input, and I need to verify if the date is right, wether it is dd/mm/aaaa or mm/dd/aaaa.
If possible, without using regExp. I already made this function out of StackOverflow RegExp :
function validateDateRegExp(field){
var date=field.value;
var regExp1 = /^(((0[1-9]|[12]\d|3[01])[\s\.\-\/](0[13578]|1[02])[\s\.\-\/]((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)[\s\.\-\/](0[13456789]|1[012])[\s\.\-\/]((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])[\s\.\-\/]02[\s\.\-\/]((19|[2-9]\d)\d{2}))|(29[\s\.\-\/]02[\s\.\-\/]((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/;
var regExp2 = /^((\d{2}(([02468][048])|([13579][26]))[\-\/\s]?((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|([1-2][0-9])))))|(\d{2}(([02468][1235679])|([13579][01345789]))[\-\/\s]?((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\s(((0?[1-9])|(1[0-2]))\:([0-5][0-9])((\s)|(\:([0-5][0-9])\s))([AM|PM|am|pm]{2,2})))?$/;
if(!(regExp1.test(date)||regExp2.test(date))){
alert(date);
document.getElementById('fld_CS_BuyingDate').value="";
}
}
I'm looking for a solution since 2 days, but the answers are not clear, or the problem is not the same.
Does anyone have any idea on how I could work that out ?
Thanks for the future answers
I'm having an issue supporting multiple formats for a date input that is submitted from my view.
For example, if a user submits a date of birth as 03/04/2016 it parses and works just fine.
I need to allow the user to submit as above, or as 3/4/2016, or even as 342016.
This is how I have it set to convert and send as part of my payload in my controller.
DateOfBirth: (new Date($scope.dob)).toJSON()
As I said above, works fine when using 03/04/2016 format, but I need to support if a user enters other ways as well.
Can someone point me in the right direction?
This may work if there are delimiters in the date.
var regEx1 = /^(\d?\d)[\/\.\-](\d?\d)[\/\.\-](\d\d\d\d)$/; //Catch the regular way
var matches = regEx1.exec($scope.dob);
if (matches && matches.length >= 4) {
DateOfBirth: (new Date(matches[3],matches[2],matches[1])).toJSON()
} else {
alert("Invalid date, please don't forget the delimiters");
}
If there aren't delimiters in the date I don't think there's a general way to deal with this unless the date is exactly 6 or 8 digits long.
you can try this lib
MOMENT.JS
Parse, validate, manipulate, and display dates in JavaScript.
moment().format('L'); // 03/04/2016
moment().format('l'); // 3/4/2016
moment(any date).format('DDMMYYYY') // you can to combine format output
moment("12-25-1995", "MM-DD-YYYY");
OR UI-MASK
I am trying to get the age based on two dates: Date of birth and date of visit. Everytime I try to use getFullYear(); in the following manner: I get the error that
var b = getField("dob").value;
var c = b.getFullYear();
I get this error in the console.
b.getFullYear is not a function
2:Console:ExecException in line 2 of function top_level, script Console:Exec
TypeError: b.getFullYear is not a function
2:Console:Exec
undefined
What am I doing wrong? I've tried all sorts of ways to make this work and the only thing that does is I use substring() to get the last 4 digits of the date.
The date is formatted as mm\dd\yyyy.
Thanks!
try var b = new Date(getField("dob").value);
You can check for type of b to be of Date
For Eg:
var b = getField("dob").value;
if(Object.prototype.toString.call(b) === '[object Date]')
{
var c = b.getFullYear();
}
else{
alert("Not valid date");}
In a comment you said
the dob field is a text field formatted as dd/mm/yyyy Is that what you were asking
...and you've tagged your question acrobat, so I'm guessing this is JavaScript running within a PDF, not in a web browser.
On browsers, if you try to parse a string in the form dd/mm/yyyy (say, 03/05/2014), regardless of the locale of the browser (U.S., UK, Spanish, Russian, Japanese), the browser will try to read it as mm/dd/yyyy (American format, month-day-year) first. This is not specified anywhere (certainly not in the JavaScript spec), but it's been true of every browser I've ever tried it on.
If Acrobat does the same thing, and you have the text field formatted as dd/mm/yyyy, you'll run into trouble — is 03/05/2014 May 3rd or March 5th? In the format you're using, it's May 3rd, but in American format it's March 5th.
Unless you want to test Acrobat in multiple locations (or can find a reference promising you how it will parse that string), you'll want to parse it yourself.
If you just want the year at the end, that's fairly simple:
var match = getField("dob").value.match(/(\d{4})\s*$/);
var year = match ? match[1] : undefined;
That'll be a string. If you want to make it a number, you can change the second line slightly:
var year = match ? +match[1] : undefined;
(The + converts match[1], which we know is all digits, to a number.)
If you want the full date, there are several answers here on SO that demonstrate parsing a date with a well-defined format.
I have asp (classic) script and within javascript code. From database I get date in format yyyy-mm-dd (2010-10-14) and save in variable. Then, I pass this variable to javascript method:
Response.Write("<a href='Javascript: PassDate("&OurDate&","&Val1&","&Val2&");'>Pass</a>")
This method code is:
function PassDate(OurDate, Val1, Val2)
{
window.open("newsite.asp?date="+OurDate+"&val1="+Val1+"&val2="+Val2");
}
When I try get date on new site (newsite.asp) by Request.QueryString("date"), I get calculate value 1996 (2010-10-14 = 1986), instead date '2010-10-14'.
I try various ways to solve this problem, but it still calculate value.
For example, I try replace "-" for ".", but I get error about missing ")".
Use commas instead of dashes. That way, each part will be seen as a separate argument to the JavaScript function.
Have you considered saving the date using the javascript date object and then passing that to your method?
My javascript is a little rusty, but I believe it would be something like the following:
var dateParts = split(OurDate, "-");
var myDate = new Date(dateParts[0], dateParts[1], dateParts[2]);
I'm using the excellent (but large) DateJS library to handle dates and times in my webapp. I just came across something that I'm not sure how to handle.
I want my users to be able to enter Time strings only, without a date, but they should be able to enter it in any manner they please. For instance:
5:00 pm
17:00
5:00pm
5:00p
5p
etc.
Using Date.parse(value) converts these strings into a full date, which is exactly what I want. However, it also allows the user to enter any other part of a date string, such as:
sat 5pm
1/1/2010 5pm
etc.
I'm trying to use DateJS to validate an input field for a time value. Something like:
function validateTime(value) {
return Date.parse(value) !== null;
}
Is there a way to use DateJS features to solve this? There are other SO questions that provide solutions, but if DateJS has a way to do this, I don't really want to add more custom code to my app to do this.
Shortly after asking my question, I discovered that Date.parseExact() can take an array of format strings. Somehow I'm missed that. I managed to get something working with the following code:
function validateTime(input) {
return Date.parseExact(input, [
"H:m",
"h:mt",
"h:m t",
"ht","h t"]) != null ||
Date.parseExact(input, [
"h:mtt",
"h:m tt",
"htt","h tt"]) != null;
};
Note that some formats don't seem to be able to be included together at the same time, which is why I split them into two separate parseExact() calls. In this case, I couldn't include any string that contained a single t in it with format strings that contained a double tt in it.
The additive approach seems cumbersome. Takes away the beauty of DateJS in my opinion. I needed the same solution and decided to just sneakily append the date in front of my input string before parsing with DateJS:
var parsed = Date.parse(Date.today().toString('M/d/yyyy') + ' ' + this.value);
if (parsed) {
alert(parsed.toString('h:mm tt'));
}
Now DateJS will not be sniffing around for any of its date-part parsing patterns, as you have already subbed it in.
Hope this helps someone!