1

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));
1
  • You will find Here How to Convert String to Int using Javascript and jquery Commented Sep 2, 2012 at 13:56

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Pointy. Makes total sense.
2

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 );​

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.