57

I need javascript code to get first day of year. e.g. It will be 1st Jan 2013 for this year.

For next year it should be 1st Jan 2014. So basically 1st day of whatever is current year.

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
user1990525
  • 3,357
  • 4
  • 16
  • 13

5 Answers5

171

Create a new Date instance to get the current date, use getFullYear to get the year from that, and create a Date intance with the year, month 0 (January), and date 1:

var d = new Date(new Date().getFullYear(), 0, 1);
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • 1
    This is the best answer. – Michael Paccione May 14 '19 at 09:00
  • Would you please add a 'var' before 'd'? I cannot edit it because 'var' is only three characters. – Benisburgers Feb 11 '20 at 14:29
  • 2
    This solution gives me the last day of the previous year `2019-12-31T23:00:00.000Z`. This gives me the first day: `new Date(new Date().getFullYear(), 0, 1, 1)` – sunwarr10r Oct 09 '20 at 10:18
  • @WatermelonSugar: The code in the example produces a date in the local time zone, but you show a date in UTC, so the difference may come from how you display the date. – Guffa Oct 12 '20 at 09:35
13

var year = 2013;

var date = new Date(year, 0, 1);

console.log(date); // Tue Jan 01 2013 00:00:00 GMT+0100 (Mitteleuropäische Zeit)

You can construct Dates using new Date(YEAR,MONTH,DAY)

So giving the constructor the year you want and the first Day of the First Month, you get your Date Object

Note that the Date Object starts counting with 0 for the Month, so January == 0

M.A.K. Ripon
  • 2,070
  • 3
  • 29
  • 47
Moritz Roessler
  • 8,542
  • 26
  • 51
5

Try this one:

var timestmp = new Date().setFullYear(new Date().getFullYear(), 0, 1);
var yearFirstDay = Math.floor(timestmp / 86400000);
var day = new Date(yearFirstDay);
alert(day.getDay());

Note: that code returns number, so Sunday is 0, Monday is 1, and so on.

Nick
  • 602
  • 9
  • 22
2
var d = new Date(2013, 0, 1).getDay(); //0 is January for some reason

alert(d);
0

Check out this fiddle

year = prompt("Enter year : ");

d = new Date(year, 0,1);

var myDays=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];

alert("First Day is " + myDays[d.getDay()]);
Jacob George
  • 2,559
  • 1
  • 16
  • 28