Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 613
sijo vijayan Avatar asked Dec 09 '15 10:12

sijo vijayan


People also ask

How do I get the first day of the month in node JS?

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.

How do you find the first Date of the current 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.

How do you get the first Date of the month from a Date in JavaScript?

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!

How do I get current Date in node JS?

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


1 Answers

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

like image 112
Jxx Avatar answered Oct 18 '22 00:10

Jxx