Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the day number from moment object javascript

I have a moment data object, what i want to do is get the date number, like if 2018-12-31 is given, it should return 365.

What I've currently done is this, but I feel like this is a more brute force approach since I have to run this function over and over again. Is there a more elegant way of doing this through the momentjs library?

var day = 25;
var mon = 12;
var year = 2018;
var sum = 0;
var days = 0;
var month_day = [31,28,31,30,31,30,31,31,30,31,30,31];
for ( var i = 0; i < mon; i++){
    sum += month_day[i];
}

days = sum - (month_day[mon-1] - day);
console.log(days)
like image 509
Nimesha Kalinga Avatar asked Sep 10 '18 03:09

Nimesha Kalinga


People also ask

How do you find the day of the month moment?

You can use moment(). format('DD') to get the day of month. var date = +moment("12-25-1995", "MM-DD-YYYY").

How do you find the day and month from date in moment?

The moment(). daysInMonth() function is used to get the number of days in month of a particular month in Node.

How do you extract time from a moment?

The moment(). hour() Method is used to get the hours from the current time or to set the hours.


3 Answers

You can use the dayOfYear() function:

const day = 25;
const month = 12 - 1; // months are 0-based when using the object constructor
const year = 2018;
const date = moment({day, month, year});

console.log(date.dayOfYear()); // 359
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
like image 133
Robby Cornelissen Avatar answered Oct 08 '22 10:10

Robby Cornelissen


You can do it without momentjs

let year = 2018;
let month = 12 - 1;
let day = 25;
let dayOfYear = (Date.UTC(year, month, day) - Date.UTC(year, 0, 1)) / 86400000 + 1;
console.log(dayOfYear);
like image 25
Dmitry Kolchev Avatar answered Oct 08 '22 08:10

Dmitry Kolchev


The moment documentation is helpful: https://momentjs.com/docs/#/get-set/day-of-year/

var day = 25;
var mon = 12;
var year = 2018;
console.log(moment().year(year).month(mon).date(day).dayOfYear());
like image 1
DrevanTonder Avatar answered Oct 08 '22 09:10

DrevanTonder