简体   繁体   中英

How can I get date in application run by node.js?

Do I have to manually run date command using child_process and fetch the result from it to get the date? Is there any other way using node?

You do that as you would in a browser:

 var datetime = new Date(); console.log(datetime);

 var datetime = new Date(); console.log(datetime.toISOString().slice(0,10));

NodeJS (and newer browsers) have a nice shortcut to get the current time in milliseconds.

var timeInMss = Date.now()

Which has a performance boost compared with

var timeInMss = new Date().getTime()

Because you do not need to create a new object.

To create a new Date object in node.js , or JavaScript in general, just call it's initializer

var d = new Date();

var d = new Date(dateString);

var d = new Date(jsonDate);

var d = new Date(year, month, day);

var d = new Date(year, month, day, hour, minute, second, millisecond);

Remember that Date objects can only be instantiated by calling Date or using it as a constructor; unlike other JavaScript object types, Date objects have no literal syntax

You would use the javascript date object:

MDN documentation for the Date object

var d = new Date();

GMT -03:00 Example

new Date(new Date()-3600*1000*3).toISOString();

Node.js is a server side JS platform build on V8 which is chrome java-script runtime.

It leverages the use of java-script on servers too.

You can use JS Date() function or Date class.

I had an experience about dates on NodeJS with MongoDB database and I want to share it on this page as well,

I was setting a default value to a date field on Mongoose Schema as below code:

{ type: Date, default: new Date() }

but after one day, I've realized that default value is still getting date belong to yesterday. it needs to be written as below:

{ type: Date, default: () => { return new Date() } }

Otherwise it always getting process start date, thanks to @lineus's comment on the page below:

https://github.com/Automattic/mongoose/issues/3675

First, get the date

const date = Date()

create new date object

const new_date = new Date(date)

Then you can get all the details

const hours = new_date.getHours()
const minutes = new_date.getMinutes()
var datetime = Date.now();
console.log(datetime); // return in milliseconds

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM