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)
You can use moment(). format('DD') to get the day of month. var date = +moment("12-25-1995", "MM-DD-YYYY").
The moment(). daysInMonth() function is used to get the number of days in month of a particular month in Node.
The moment(). hour() Method is used to get the hours from the current time or to set the hours.
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>
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);
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With