Get the day number from moment object javascript

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)






I know this is asked for php, but i want to know is, whether is there a elegant way of doing this using moment

– Nimesha Kalinga
Sep 10 '18 at 3:51






Not only brute force, but also incorrect because it ignores leap years.

– Robby Cornelissen
Sep 10 '18 at 3:52




3 Answers
3



You can use the dayOfYear() function:


dayOfYear()




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);






Info: momentjs use a somewhat similar approach.

– user202729
Sep 10 '18 at 11:30



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


moment


var day = 25;
var mon = 12;
var year = 2018;
console.log(moment().year(year).month(mon).date(day).dayOfYear());



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)