Introduction to DateFormat Library
The dateformat
library is a powerful tool for formatting dates and times in JavaScript applications. It provides a variety of formatting options and functions that make it easy to display dates and times in a user-friendly manner. This detailed guide will introduce you to the most useful APIs provided by the dateformat
library, complete with multiple code examples and an application sample.
Basic Formatting
To use dateformat
, you first need to import it:
const dateFormat = require('dateformat');
Here’s a simple example of formatting the current date:
const now = new Date(); console.log(dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT"));
Default Masks
The dateformat
library comes with several default masks for common date formats:
console.log(dateFormat(now, "shortDate")); console.log(dateFormat(now, "mediumDate")); console.log(dateFormat(now, "longDate")); console.log(dateFormat(now, "fullDate"));
Custom Masks
You can also define your own custom date masks:
dateFormat.masks.custom = "dddd, mmmm dS, yyyy"; console.log(dateFormat(now, "custom"));
Time Formatting
Format the time portion of a Date object easily:
console.log(dateFormat(now, "h:MM:ss TT"));
UTC Mode
Format dates in UTC mode using the UTC:
prefix:
console.log(dateFormat(now, "UTC:yyyy-mm-dd HH:MM:ss"));
Modifiers
Apply various modifiers to customize the output further:
console.log(dateFormat(now, "dddd, mmm dS, yyyy, h:MM TT Z")); console.log(dateFormat(now, "isoDateTime"));
Application Example
Below is a practical example of a Node.js application that uses the dateformat
library to display and log current server time in different formats:
const http = require('http'); const dateFormat = require('dateformat'); const server = http.createServer((req, res) => { const now = new Date(); res.writeHead(200, {'Content-Type': 'text/plain'}); res.write(`Current Date and Time: ${dateFormat(now, "fullDate")} ${dateFormat(now, "isoTime")}\n`); res.write(`Custom Format: ${dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT")}\n`); res.end(); }); server.listen(3000, () => { console.log("Server started on port 3000"); console.log(`Current Date and Time: ${dateFormat(new Date(), "fullDate")} ${dateFormat(new Date(), "isoTime")}`); });
Conclusion
The dateformat
library is an invaluable tool for JavaScript developers who need precise and versatile date and time formatting. The above examples and application snippets demonstrate its capabilities and ease of use. Utilize these examples and the library’s documentation to integrate date formatting into your projects effortlessly.
Hash: 2db5f712215bb088959b04ba060bc87034f262baad97f3540985e34daffa2468