How to get the first date of the current month in Node.js?

I am trying to get the first and last date of the current month using Node.js.

The following code works fine in a browser (Chrome):

var date = new Date(), y = date.getFullYear(), m = date.getMonth(); var firstDay = new Date(y, m, 1); var lastDay = new Date(y, m + 1, 0); console.log(firstDay); console.log(lastDay); 

But it shows a different result in Node.js. How can i fix this?

+5
source share
3 answers

Changing your own Date object in the accepted answer is bad practice; do not do this ( fooobar.com/questions/14046 / ... )

You should use moment.js to provide you with a consistent environment for processing dates in JavaScript between node.js and all browsers - see this as an abstraction layer. http://momentjs.com/ - it is quite easy to use.

A very similar example: fooobar.com/questions/96305 / ...

You can try it online at https://tonicdev.com/jadaradix/momentjs

+3
source

The browser window displays the date in the current time zone, node.js shows the date time zone GMT / Zulu.

(Edit: code added). Something like that

 var offset = (new Date().getTimezoneOffset() / 60) * -1; var d = new Date(); var tmpDate = new Date(d.getTime()+offset); var y = tmpDate.getFullYear(); var m = tmpDate.getMonth(); var firstDay = new Date(y, m, 1); var lastDay = new Date(y, m + 1, 0); console.log(tmpDate.toString()); console.log(firstDay.toString()); console.log(lastDay.toString()); 
0
source

Look at the code

 <html> <head> <title>Please Rate if it helps</title> <script> Date.prototype.getMonthStartEnd = function (start) { var StartDate = new Date(this.getFullYear(), this.getMonth(), 1); var EndDate = new Date(this.getFullYear(), this.getMonth() + 1, 0); return [StartDate, EndDate]; } window.onload = function () { document.write(new Date().getMonthStartEnd()); } </script> </head> <body> </body> </html> 
-2
source

Source: https://habr.com/ru/post/1237740/


All Articles