0
var date = '04/04';<br>
alert(new Date(date));<br>

//now year 2013<br>
//result Wed Apr 04 <b>2001</b>

I want

//result Wed Apr 04 <b>2013</b>
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
Zamakshari
  • 43
  • 1
  • 5
  • strange (for me) Anyhow, I did something like this to solve it `alert(new Date(date + " " + new Date().getFullYear()));`. Not sure whether it is correct or not though. – Mr_Green Jul 30 '13 at 04:47

5 Answers5

2

You can get the current date by new Date(); So current year can be found by:

var currentDate = new Date();
  //this would return 2013

So following code would do the work for getting correct date:

var currentDate = new Date();
var currentYear = currentDate.getFullYear();

var date = "04/04";              //the date entered
var comp = date.split('/');
var m = parseInt(comp[0], 10);   //this would give you the entered month
var d = parseInt(comp[1], 10);   //this would give you the entered date

var correctDate = new Date(currentYear, m - 1, d);
correctDate.toDateString();   //this line will return the date

Hope it helps.

Ali Shah Ahmed
  • 3,263
  • 3
  • 24
  • 22
0

Set the parts individually with the setX() functions.

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
alex
  • 479,566
  • 201
  • 878
  • 984
0
var nowYear=new Date().getFullYear(); //current year

var date = '04/04/'+nowYear.toString();

alert( new Date(date));

http://jsfiddle.net/LhXH4/

is that really returning Wed Apr 04 2001? instead of invalid date? without year in string , how did it get parsed?

0
var date = '04/04';
date = new Date(date);
date = new Date(2013, date.getMonth(), date.getDate());
alert(date);
Prash
  • 1,122
  • 1
  • 8
  • 10
0

With static year it will be:

var date = '04/04';
alert(new Date('2013/'+date));

where date format is yyyy/MM/dd

Alex
  • 11,451
  • 6
  • 37
  • 52