Introduction
In JavaScript, processing and formatting of dates and times is a very common requirement. JavaScript provides built-inDate
Objects are used to operate dates and times, but their formatting functions are relatively limited. To make dates more convenient, it is often necessary to incorporate some additional tools or libraries. This article covers date formatting tips from basic to advanced.
Using native Date objects
We can create it in a variety of waysDate
Object, such as passing in a specific timestamp, string, or specified year, month, day, hour, minute, and second.
const date = new Date(); const date1 = new Date(2024, 8, 13); // Note: Month starts from 0const date2 = new Date("2024-09-13T10:20:30Z"); const date3 = new Date(1694596830000); // Time stamp
Get the various parts of the date and time
JavaScript provides various methods to get different parts of a date, such as year, month, day, hour, minute, etc.
const date = new Date(); (()); // Get the year(()); // Get month, 0 means January, 11 means December(()); // Get a day of the month(()); // Get hours(()); // Get minutes(()); // Get seconds(()); // Get the day of the week, 0 means Sunday
Format date string
By default,Date
Objects provide several built-in methods to convert dates to strings:
-
toDateString()
: Returns a short representation of the date, e.g."Fri Sep 13 2024"
. -
toTimeString()
: Returns the time part, e.g."10:20:30 GMT+0000 (Coordinated Universal Time)"
. -
toISOString()
: Returns the standard ISO 8601 format, e.g."2024-09-13T10:20:30.000Z"
. -
toLocaleDateString()
: Set the format date according to localization. -
toLocaleTimeString()
: Set the formatting time according to localization.
const date = new Date(); (()); // 2024-09-13T10:20:30.000Z (()); // Fri Sep 13 2024 (('zh-CN')); // 2024/9/13 (('en-US')); // 9/13/2024, 10:20:30 AM
Custom formatting
In actual development, in addition to obtaining date data through native Date objects. It is also a considerable part of the application scenarios that require custom date formats. At this time, you need to manually splice or use regular expressions fromDate
Extract different parts from the object. For example:
function formatDate(date) { const year = (); const month = String(() + 1).padStart(2, '0'); // Add 1 to the month, make sure it is a double digit number const day = String(()).padStart(2, '0'); const hours = String(()).padStart(2, '0'); const minutes = String(()).padStart(2, '0'); const seconds = String(()).padStart(2, '0'); return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`; } const date = new Date(); (formatDate(date)); // 2024-09-13 10:20:30
The above is a basic version of the custom formatting method. We can expand it to support customized time formats:
function formatDate(date, format = "yyyy-MM-dd HH:mm:ss") { const year = (); const month = () + 1; const day = (); const hours = (); const minutes = (); const seconds = (); const toSymbol = () => { return hours > 12 ? "PM" : "AM"; }; const hasSymbol = ('a') > -1 const symbols = { yyyy: year, MM: `${month}`.padStart(2, "0"), dd: `${day}`.padStart(2, "0"), HH: `${hours}`.padStart(2, "0"), hh: hasSymbol && hours > 12 ? hours - 12 : hours, mm: `${minutes}`.padStart(2, "0"), ss: `${seconds}`.padStart(2, "0"), // a means 12-hour system a: toSymbol(), }; let time = format; (symbols).forEach((key) => { time = (key, symbols[key]); }); return time; } // 2024-10-26 PM 1:06:43 12-hour system(formatDate(new Date(), "yyyy-MM-dd a hh:mm:ss"));
Localized formatting
In addition to the formatting requirements for date custom formats, for large platform projects, localized formatting or internationalized date formatting support is required. APIProvides a standard interface for our international date format.
It is an internationalization tool built into the JavaScript language that allows us to format dates locally.
const date = new Date(); const formatter = new ('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false, }); ((date)); // 2024/09/13 10:20:30
You can control the output format by modifying the options, for example:
-
year
,month
,day
: Control the date part -
hour
,minute
,second
: Control the time part -
hour12
: Whether to use the 12-hour system
Browser compatibility
The browser support is still ideal, and it is currently a good choice if you want to use a standard date international format solution.
Processing time zone
In addition to dealing with personalized date formats and international date formats, another issue for dates that large applications need to deal with is dealing with across time zone date data.
Native JavaScript time zone
JavaScript nativeDate
By default, the object displays time according to the system's time zone. If you need to convert the time zone, you can usetoLocaleString
method:
const date = new Date(); (('en-US', { timeZone: 'America/New_York' })); // Convert to New York time
Using moment-timezone
// Install moment-timezone: npm install moment-timezoneconst moment = require('moment-timezone'); const newYorkTime = ("America/New_York").format('YYYY-MM-DD HH:mm:ss'); (newYorkTime); // Current time in New York
Use the dayjs time zone plugin
const dayjs = require('dayjs'); const utc = require('dayjs/plugin/utc'); const timezone = require('dayjs/plugin/timezone'); (utc); (timezone); const newYorkTime = dayjs().tz("America/New_York").format('YYYY-MM-DD HH:mm:ss'); (newYorkTime); // Current time in New York
Using third-party libraries
In addition to personally dealing with various date format issues, using third-party libraries to deal with date format issues is also a good choice. The following will introduce some mainstream third-party libraries for processing date data.
(Not recommended for new projects)
Although it was once a standard library for processing dates, new projects are no longer recommended due to large size and performance issues. It is officially recommended to use native APIs or other lighter libraries.
// Installation: npm install momentconst moment = require('moment'); const date = moment().format('YYYY-MM-DD HH:mm:ss'); (date); // 2024-09-13 10:20:30
is a modern, lightweight date processing library with API design similar to .
// Installation: npm install dayjsconst dayjs = require('dayjs'); const date = dayjs().format('YYYY-MM-DD HH:mm:ss'); (date); // 2024-09-13 10:20:30
Supports a variety of plug-in extensions, such as time zone, relative time, etc.
date-fns
date-fns
is another popular date processing library that is powerful and modular. You can introduce only some of the features as needed.
// Install date-fns: npm install date-fnsconst { format } = require('date-fns'); const date = new Date(); (format(date, 'yyyy-MM-dd HH:mm:ss')); // 2024-09-13 10:20:30
date-fns
Many practical functions are provided, such as formatting, comparison, time calculation, etc., which are very suitable for handling complex date operations.
Summarize
For date formatting, native JavaScript methods are suitable for handling simple date and time formatting. useDate
Objects combined with manual stitching of strings can meet most needs.This JavaScript built-in international date formatting tool is suitable for scenarios where localized formatting is required.
And date-fns provides more powerful features and a simple API, suitable for handling complex date operations and formatting requirements. You can choose the appropriate solution according to your actual application.
The above is the detailed content shared by JavaScript date formatting skills. For more information about JavaScript date formatting, please follow my other related articles!