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.
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
try{
var hdnPassenger = $("#ctl00_ContentPlaceHolder1_hdnPassenger").val();
var newTr = $("#hdnCtl").html();
newTr = newTr.replace(/_ID/g, hdnPassenger);
}
catch(ex){
alert(ex);
}
Above code is working fine in the internet explorer, but displayed the following error in the mozilla firefox
InternalError: regular expression too complex
Having done some research into this problem, there are two possible reasons for this error:
The actual regex too complex (not in your case, as you only have /_ID/)
The length of the string you're trying to do the substitution on (I don't know what it is, but probably quite long). It seems that there's some hard-coded limit in some versions of firefox, but I can't vouch for that.
I suggest you do two this: add the values of your hdnPassenger and newTr variables - and at the same time google firefox regular expression too complex - there are plenty of hits.
I want to format number using javascript as below:
10.00=10,00
1,000.00=1.000,00
Every browser supports Number.prototype.toLocaleString(), a method intended to return a localized string from a number. However, the specification defines it as follows:
Produces a string value that represents the value of the Number formatted according to the conventions of the host environment's current locale. This function is implementation-dependent, and it is permissible, but not encouraged, for it to return the same thing as toString.
Implementation-dependant means that it's up to the vendor how the result will look, and results in interoperability issues.
Internet Explorer (IE 5.5 to IE 9) comes closest to what you want and formats the number in a currency style - thousands separator and fixed at 2 decimal places.
Firefox (2+) formats the number with a thousands separator and decimal places but only if applicable.
Opera, Chrome & Safari output the same as toString() -- no thousands separator, decimal place only if required.
Solution
I came up with the following code (based on an old answer of mine) to try and normalize the results to work like Internet Explorer's method:
(function (old) {
var dec = 0.12 .toLocaleString().charAt(1),
tho = dec === "." ? "," : ".";
if (1000 .toLocaleString() !== "1,000.00") {
Number.prototype.toLocaleString = function () {
var neg = this < 0,
f = this.toFixed(2).slice(+neg);
return (neg ? "-" : "")
+ f.slice(0,-3).replace(/(?=(?!^)(?:\d{3})+(?!\d))/g, tho)
+ dec + f.slice(-2);
}
}
})(Number.prototype.toLocaleString);
This will use the browser's built-in localization if it's available, whilst gracefully degrading to the browser's default locale in other cases.
Working demo: http://jsfiddle.net/R4DKn/49/
I know this solution using NumberFormat but it is necessary to convert the values to string.
https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/NumberFormat
// Remove commas
number = "10,000.00".replace(/,/g, '');
// Create a NumberFormat type object
var formatter = new Intl.NumberFormat('de-DE', {
minimumFractionDigits: 2
});
// Apply format
console.log(formatter.format(number));
output:10.000,00
Javascript doesn't provide this functionality itself, but there are a number of third-party functions around which can do what you want.
Note, whichever method you use, you should be careful to only use the resulting string for display purposes -- it won't be a valid number value in Javascript after you've converted the decimal point to a comma.
The quickest solution I can offer is to use the number_format() function written by the phpJS people. They've implemented Javascript versions of a load of commonly-used PHP functions, including number_format(), and this function will do exactly what you want.
See the link here: http://phpjs.org/functions/number_format
I wouldn't bother about taking the whole phpJS library (a lot of it is of questionable value anyway), but just grab the 20-odd line function shown on the page linked above and paste it into your app.
If you want a more flexible solution, there are a number of JS functions around which simulate the printf() function from C. There is already a good question on SO covers this. See here: JavaScript equivalent to printf/string.format
Hope that helps.
Apparently javascript date object's method getYear() returns different result between IE8 and Firefox3.6 (I have those 2 on my machine, not sure other browser or version)
Date d = new Date();
alert(d.getYear());
FF3.6 ==> 111 (year since 1900? i guess)
IE8 ===> 2011
I have been only testing on Firefox and now my Javascript code that adjust returned value of getYear() is now giving me 3911 because of my coding.
var modified = d.getYear() + 1900
On Firefox it return 2011. But if I apply this approach on IE8, it return 3911.
I could add logic to distinguish IE and Firefox but I don't want to add such if/else everywhere in my code wherever there are browser dependent parts like this. Is there other way to approach this problem?
var browserName=navigator.appName;
if (browserName=="Netscape") {
var modified = d.getYear() + 1900
}
else if(browserName=="Microsoft Internet Explorer") {
var modified = d.getYear();
}
Use getFullYear() instead of getYear().
try to use getFullYear() instead getYear
If IE8 is giving you 2011, It's a bug in IE8 (and earlier, see update below). getYear is defined in the specification (Section B.2.4) as being:
Let t be this time value.
If t is NaN, return NaN.
Return YearFromTime(LocalTime(t)) − 1900.
Thus right now, 111 is the correct value. That definition is unchanged from the 3rd edition, so we're talking ~12 years of specified behavior.
As others have said, use getFullYear to get a more useful value, but that's an IE8 bug if it's truly as you say (I don't have IE8 handy to check).
Update: Well I'll be. Just tried it, and Microsoft did get it wrong. IE6, IE7, and IE8 all say "2011". The good news is they've finally fixed it, IE9 says "111" as it should. You can try it in your browser here: http://jsbin.com/ofuyi3
Don't rely on product versions when you don't have to. Instead, rely on the difference you want to correct itself. If you wanted getYear's correct value, you could get it using
Date d = new Date();
var year = d.getYear();
if (year < 1900) { // Should always be true, but isn't in older IE.
year += 1900;
}
I realise people have suggested a better way of getting the result, but I thought the actual question was worth answering.
Use date.getFullYear();
blah.. gotta answer with at least 30 characters...
The following code results in "undefined" for lastIndex:
var a = /cat/g;
var l = "A test sentence containing cat and dog.";
var r = a.exec(l);
document.write(r.lastIndex);
However, it works perfectly for r.index (and r.input).
I am using Firefox. Does anybody have a clue?
EDIT: OK, the above code works perfectly in IE! Further, in Firefox, it works perfectly if instead of calling r.lastIndex on line 5, a.lastIndex is called. It appears that Firefox does not return lastIndex property in the result - rather sets the property for the pattern invoking the exec() only. Interesting that IE sets both.
This is one of those places where Microsoft decided to add some stuff to the language and act as if it was supposed to be there. Thankfully, they are now cleaning up their act and documenting such nonsense.
To be clear: Firefox is correct according to the ECMAScript Language Specification 3rd Edition (PDF, 705KB).
IE is not correct; its behaviour is a proprietary extension. There is no reason to believe that this IE-specific behaviour will ever be supported by any other browser. It certainly isn't at the moment. See JScript Deviations from ES3 (PDF, 580KB, by Pratap Lakshman of Microsoft Corporation) Section 4.6 for more on this particular deviation from the spec, including tests showing no support on other browsers.
Note also that this may not even be supported in the future by IE: a number of proprietary IE CSS-related mechanisms are disabled by default on IE8-in-IE8-mode, and future implementations of JScript may find a reason to similarly disable this extension to the language.
lastIndex is a property of a RegExp object. So try this:
a.lastIndex
To avoid all the weird, try this
var a = /cat/g;
var l = "A test sentence containing cat and dog.";
var r = a.exec(l);
var lastIndex = (r!=null) ? l.indexOf(r[0])+r[0].length : 0;
It is used here: http://www.pagecolumn.com/tool/regtest.htm