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.
Related
This problem is driving me nuts. While my code works fine on Firefox and Google chrome, it is failing on the Internet explorer on Windows 10. But the problem is really weird.
// If I hard code this value, it works fine,
// But the same thing generated by the program fails!
//var dateStr = '2016-08-04 01:38:49'
alert(dateStr)
var a = dateStr.split(" ");
d = a[0].split("-");
t = a[1].split(":");
return new Date(d[0],(d[1]-1),d[2],t[0],t[1],t[2]);
The variable dateStr is filled by my program, and with it the returned date always comes out to be Invalid. However, if I copy the value of dateStr from the alert box, and later hard code the value of dateStr with it, a valid date is returned. What is going on? Am I missing something here? I suspect, this has to do something with unicode strings and stuff. What it could be?
I think the problem is, that your string includes some hidden chars to support e.g. right-to-left, ..
So your input params to the new Date() cntr are invalid.
Plase notice: if you use dateTime string created by the current system this may cause issues because your parser only supports YYYY-MM-DD hh:mm:ss which is a format based on your system localization and may return a completely different string if your localization is Chinese or Korean
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 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.
How can I check if date is in given format or not. It must be function like this
function isInGivenFormat(date,format)
{
//some checking
}
For example, isInGivenFormat("12:45:02","hh:mm:ss") must return true and isInGivenFormat("12:45:02 PM","hh:mm:ss") must return false.
How can I achive this functionality with Javascript/Jquery?
I would urge you to look at the Date.js library. It handles this scenario (and much more).
In particular the parseExact() method solves this problem.
Date.parseExact ( String dateString, String formatStringOrArray ) : Date
Converts the specified string value into its JavaScript Date equivalent using the specified format (string) or formats (array). The format of the string value must match one of the supplied formats exactly.
Examples
Date.parseExact("12:45:02 PM","hh:mm:ss"); // returns null
Date.parseExact("10/15/2004", "M/d/yyyy"); // The Date of 15-Oct-2
var dateCheck = /^\d{2}:\d{2}:\d{2}$/.test(date)
if(!dateCheck){
//not a match
}
You can use the Date.parseExact() function of the date.js library
You need to use the regular expressions. This link could help:
regex in javascript
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]);