user12723516
user12723516

Reputation: 3

The beginning of the year of the set date?

How can I find the beginning of the year for a set date? That is, let's say I set the date 2018-07-28, then the result should be 2018-01-01. I know that for example in Rails there is such a function as beginning_of_year.

Is there anything similar for nodejs?

Or maybe someone already has a similar for javascript?

Upvotes: 0

Views: 785

Answers (3)

Pushprajsinh Chudasama
Pushprajsinh Chudasama

Reputation: 7949

You can do with the help of moment library .

var thisYear = (new Date()).getFullYear();    
var start = new Date("1/1/" + thisYear);
var defaultStart = moment(start.valueOf());

It is easy way and also a efficient way .

Upvotes: 0

divya_kanak
divya_kanak

Reputation: 142

First, Get the year from date and concatenation of string "01-01". Please check below :

new Date('2018-07-28').getFullYear()+'-01-01'

But if you wants to create Date object for year begging day. Please check below :

new Date(new Date('2018-07-28').getFullYear(), 0, 1)

Upvotes: 0

YellowAfterlife
YellowAfterlife

Reputation: 3192

You could use getFullYear and construct a new Date object

function beginning_of_year(date) {
    return new Date(date.getFullYear(), 0);
}
beginning_of_year(new Date()); // Wed Jan 01 2020 00:00:00

Upvotes: 2

Related Questions