Typescript

How to Get Current Date and Time in Node.js With Examples

How to Get Current Date and Time in Node.js With Examples

In this tutorial, we’ll explore various methods to obtain the current date and time in Node.js applications. Node.js utilizes the JavaScript Date object, which is built-in and requires no additional module imports. We’ll cover how to retrieve the current date, month, year, hour, minutes, and seconds, as well as formatting options like YYYY-MM-DD hh:mm:ss, YYYY-MM-DD, and DD-MM-YYYY.

  1. Basic Date and Time Retrieval

Let’s start with a simple example of fetching the current date and time:

const express = require('express');
const app = express();

const currentDateTime = new Date();
console.log(currentDateTime);

app.listen(3000);

Output: 2023-04-22T08:45:25.558Z

  1. Formatting Date and Time

Here’s how to format the date and time in YYYY-MM-DD HH:MM:SS format:

const express = require("express");
const app = express();

const now = new Date();

const date = ("0" + now.getDate()).slice(-2);
const month = ("0" + (now.getMonth() + 1)).slice(-2);
const year = now.getFullYear();
const hours = now.getHours();
const minutes = now.getMinutes();
const seconds = now.getSeconds();

console.log(`${year}-${month}-${date}`);
console.log(`${year}-${month}-${date} ${hours}:${minutes}:${seconds}`);

Output:
2023-04-22
2023-04-22 10:27:21

  1. Getting Current Timestamp

To retrieve the current timestamp in milliseconds or seconds:

const timestampMs = Date.now();
console.log(timestampMs);

const timestampSec = Math.floor(timestampMs / 1000);
console.log(timestampSec);

Output:
1682139523068
1682139574

  1. Converting Timestamp to Date

Here’s how to convert a timestamp back to a formatted date:

const timestamp = Date.now();
const dateTime = new Date(timestamp);

const date = dateTime.getDate();
const month = dateTime.getMonth() + 1;
const year = dateTime.getFullYear();

console.log(`${year}-${month}-${date}`);

Output:
2023-04-22

By mastering these techniques, you’ll be able to effectively manage date and time operations in your Node.js applications. Remember to consider time zones and localization when working with dates and times in production environments.

For more advanced date and time manipulation, consider using libraries like Moment.js or date-fns, which offer additional formatting options and timezone handling capabilities.

Suggested Articles

Leave a Reply

Your email address will not be published. Required fields are marked *