Question

I want to parse a date and create a datetime object. I am using the following code:

function generateDateObject (dateString, timeString) {
    // Date string has the format: dd/mm/yy (4 digit year)
    // Time string has the format: hh:mm
    var dateSplit = dateString.split('/');
    var timeSplit = timeString.split(':');

    var date   = parseInt(dateSplit[0]);
    var month  = parseInt(dateSplit[1])-1; // Counting starts from zero
    var year   = parseInt(dateSplit[2]);
    var hour   = parseInt(timeSplit[0]);
    var minute = parseInt(timeSplit[1]);
    var second = 0;
    var msec   = 0;

    var result = new Date(year, month, date, hour, minute, second, msec);    
    return result;
};

However, strangely enough, under Opera when one tries to parse today's date which is the string "08", the parsed integer is 0. Here I should mention that the function works as expected under Firefox, Chrome, and Safari.

So, my question is: Do I really have to add more logic into the function and check if the first character of the date, the month, the hour, and the minute start with "0" and remove that character so that I can guarantee that the script behaves correctly under Opera as well?

Isn't this something trivial that should really work "out of the box" when someone is developing and testing with Opera as well?

I am using: Opera 12.16, build 1860, under Mac OS X, 10.9.0.

Was it helpful?

Solution

Add the the radix to all parseInt() calls. Else JS will recognize "08" as being base 8, where "8" is an invalid character and thus wont be parsed.

parseInt( '08' ) == 0
parseInt( '08', 10 ) == 8

MDN docu on parseInt()

If the input string begins with "0x" or "0X", radix is 16 (hexadecimal) and the remainder of the string is parsed.

If the input string begins with "0", radix is eight (octal) or 10 (decimal). Exactly which radix is chosen is implementation-dependent.

ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet. For this reason always specify a radix when using parseInt.

If the input string begins with any other value, the radix is 10 (decimal).

OTHER TIPS

There exists an interesting alternative to parseInt: to convert a string to an integer and be really sure that this works absolutely everywhere* you should use the double bitwise NOT operator (~~) in javascript:

~~'08' == 8

This is guaranteed to work in really every browser and it is also much faster than parseInt.

*I have seen parseInt not produce correct results in older versions of IE

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top