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
LVL 1
isamesAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Julian HansenCommented:
What are you wanting - the first example is 1 Jan 2015 - are you asking how to format the date or how to set it?
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
isamesAuthor Commented:
@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
0
Julian HansenCommented:
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

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.