Link to home
Start Free TrialLog in
Avatar of isames
isames

asked on

JavaScript Dates

The following code gives me the first day of the current year in the following format:

d = new Date(new Date().getFullYear(), 0, 1) = Thu Jan 01 2015 00:00:00 GMT-0500 (Eastern Daylight Time)

What JavaScript code will give me 2015-01-01  or the first day of the current year
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of isames
isames

ASKER

@julian hansen

I want to get the date formatted as 2015-01-01 00:00:00.000

And when the year turns to 2016, it automatically changes to that year 2016-01-01
You can extend the Date prototype and add your own format function
<script>
Date.prototype.myFormat = function() {
  var dateString = this.getFullYear() +"-"+
    ("0" + (this.getMonth()+1)).slice(-2) +"-"+
    ("0" + this.getDate()).slice(-2) + " " +
    ("0" + this.getHours()).slice(-2) + ":" +
    ("0" + this.getMinutes()).slice(-2) + ":" +
    ("0" + this.getSeconds()).slice(-2) + "." +
    ("00" + this.getMilliseconds()).slice(-3);
  return dateString;
}

var d = new Date(new Date().getFullYear(), 0, 1);
console.log(d.myFormat());
</script>

Open in new window

Output
2015-01-01 00:00:00.000

Open in new window