Invalid date problems in Internet explorer - javascript

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

Related

IE11 Dates from a text field in a variable not passing properly to a service

So I have a website that uses dates to search a database. When working in Firefox and Chrome everything works just fine, but when I toss it into IE (specifically IE 11) the searching wont work. I've narrowed down my issue to when I get the data from a text field using jquery it wont pass correctly.
Here is an example:
var start= $('#startdate').val();
var end = $('#enddate').val();
$.post(this.url(), {start: start, end: end }, function(data) {
// do stuff with data
}));
Now what I have tried is messing around in the console and in the js file itself. The following things work fine:
new Date('12/1/2016'));
new Date(Date.parse('12/1/2016')));
var start = '12/16/2016';
new Date(start ));
new Date(Date.parse(start)));
But as soon as I add a jquery selector into the mix it breaks and no longer works. Has anyone encountered this before?
So I know I'm late, but I was able to figure this out. Apparently in IE just setting the value of the underlying text field wont actually update the value in the datepicker, you have to set the value yourself.
For example:
$('#startdate').datepicker('setDate', start);

how to support multiple formats when passing date through to service

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

Validating Date Time In Javascript

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.

IE charset encoding issue with JavaScript Date functions

Could someone please explain why IE has a bug when trying to use String functions on a Date function that uses the "Locale"? I think it has something to do with encoding of the characters.
Check this out jsFiddle in both IE and Chrome and you will see that in Chrome we get 4 (the correct index) and in IE we get 8. Does this have to do with ascii vs. unicode? If so, should this be a bug in IE?
var date = new Date();
var str = date.toLocaleTimeString();
jQuery('#a').text(str);
jQuery('#b').text(str.lastIndexOf(":"));
str = date.toTimeString();
jQuery('#c').text(str);
jQuery('#d').text(str.lastIndexOf(":"));
Screen shot of IE 11 jsFiddle output
Here's a modified fiddle. For whatever reason, the IE 11 string has a bunch of extra Unicode "left-to-right mark" characters embedded in it.
The code I added was
var s = '';
for (var i = 0; i < str.length; ++i)
s += str.charCodeAt(i) + ' ';
$('#c').text(s);
and an accompanying <h4> like the others.
Also see this other Stackoverflow question on the topic.
By definition Date.toLocaleTimeString() produces output according to user's preferences/defaults.
So the result (position of : ) can vary on different platforms, locales and even time of the day.
This is how Korean time looks like for example:
"오후 12:00:00"
Apparently in your case Chrome and IE have different opinion on default locale formatting.
If you have any code that relies on position of : in toLocaleTimeString() it must be refactored to something more reliable.
In some locales/settings toLocaleTimeString() may not contain : at all.

getFullYear is not a function

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.

Categories