I'm trying to get the first and last date of the current month using Node.js.
Following code is working perfectly in 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 is showing a different result in Node.js. How can I fix it?
To get the first day of a month, use the Date() constructor to create a date object, passing it the year, month and 1 for the day as parameters. The Date object will contain the first day of the month.
1. First day of current month: select DATEADD(mm, DATEDIFF(m,0,GETDATE()),0): in this we have taken out the difference between the months from 0 to current date and then add the difference in 0 this will return the first day of current month. 2.
To get the first and last day of the current month, use the getFullYear() and getMonth() methods to get the current year and month and pass them to the Date() constructor to get an object representing the two dates. Copied!
Method 1: Using Node.js Date Object The JavaScript Date Object can be used in the program by using the following command. const date = new Date();
Changing the native Date
object in the accepted answer is bad practice; don't do that ( https://stackoverflow.com/a/8859896/3929494 )
You should use moment.js to give you a consistent environment for handling dates in JavaScript between node.js and all browsers - see it as an abstraction layer. http://momentjs.com/ - it's quite easy to use.
A very similar example is here: https://stackoverflow.com/a/26131085/3929494
You can try it on-line at https://tonicdev.com/jadaradix/momentjs
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