user1032531
user1032531

Reputation: 26281

Convert JavaScript string to integer

I have a date which is provided as a string such as 09/12/2012.

If the string is today, I wish to display "Today", else I wish to display 09/12/2012.

The problem with my approach shown below is that a month like 09 gets parsed to 0 and not 9.

What is the best way to do this? Thank you

var currentDate = new Date();
dateText='09/12/2012';
var a=dateText.split('/');// mdY
$("#date").text(((parseInt(a[0])-1==currentDate.getMonth()&&parseInt(a[1])==currentDate.getDate()&&parseInt(a[2])==currentDate.getFullYear())?'Today':dateText));

Upvotes: 1

Views: 377

Answers (2)

Krycke
Krycke

Reputation: 3186

Here's a fiddle: http://jsfiddle.net/pfHA7/1/

function today()
{
    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth()+1; //January is 0!

    var yyyy = today.getFullYear();
    if(dd<10){dd='0'+dd} if(mm<10){mm='0'+mm} var today = mm+'/'+dd+'/'+yyyy;
    return today;
}

var dateText = '09/12/2012';

$("#date").text( today() == dateText ? 'Today' : dateText );​

Upvotes: 2

Pointy
Pointy

Reputation: 413709

Pass a second argument to parseInt() - specifically, 10.

$("#date").text(((parseInt(a[0], 10)-1==currentDate.getMonth()&&parseInt(a[1], 10)==currentDate.getDate()&&parseInt(a[2], 10)==currentDate.getFullYear())?'Today':dateText));

The second argument tells the function the base to use for interpreting the expression. If you don't pass that explicitly, it uses the old C conventions, which will lead to numbers starting with a zero to be interpreted as base 8 constants. That causes problems for 08 and 09.

Upvotes: 5

Related Questions