Open In App

Node.js Date.compile() API

Last Updated : 27 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The date-and-time.Date.compile() is a minimalist collection of functions for manipulating JS date and time module which is used to compile a format string for the parser.

Required Module: Install the module by npm or used it locally.

  • By using npm.
npm install date-and-time --save
  • By using CDN link.
<script src="/path/to/date-and-time.min.js"></script>

Syntax:

compile(formatString)

Parameters: This method takes the format string as the parameter.

Return Value: This method returns the formatted string date.

Example 1:

index.js




// Node.js program to demonstrate the  
// Date.compile() method
  
// Importing http module
const date = require('date-and-time')
  
// Creating object of current date and time 
// by using Date() 
const now  =  new Date('07-03-2021');
  
// Getting pattern for the future use
// by using date.compile() method
const pattern = date.compile('D/M/YYYY');
  
// Getting formatted date and time 
// by using format() method
const value = date.format(now,pattern)
  
// Display the result
console.log("Formatted date and time : " + value)


Run the index.js file using the following command:

node index.js

Output:

Formatted date and time : 1/1/1970

Example 2:

index.js




// Node.js program to demonstrate the  
// Date.compile() method
  
// Importing module
const date = require('date-and-time')
  
// Creating object of current date and time 
// by using Date() 
const now = new Date('07-03-2021');
  
// Getting pattern for the future use
// by using date.compile() method
const pattern = date.compile('M/D/YYYY');
  
// Parsing the date and time
// by using date.parse() method
const value = date.parse(now.toLocaleDateString(), pattern);
  
// Display the result
console.log("Formatted date and time: " + value)


Run the index.js file using the following command:

node index.js

Output:

Formatted date and time: 
Sat Jul 03 2021 00:00:00 GMT+0530 (India Standard Time)

Reference: https://github.com/knowledgecode/date-and-time



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads