Home > CMS Tutorial > WordPress > body text

Get the current date and time using JavaScript API to get the current date and time

WBOY
Release: 2023-09-01 21:21:02
Original
638 people have browsed it

获取当前日期和时间的利用JavaScript API获取当前日期和时间

JavaScript provides APIs that allow developers to easily work with dates, times, and time zones. In this article, we'll learn how to use JavaScript's Date and Time API to get the current date and time, format them, and perform other operations.

Introduction to Date and Time in JavaScript

Dealing with dates and times is inevitable in web development. It is used in various online applications to display dates and times, countdown timers, and timestamps, as well as to schedule events and handle user interaction with time elements. JavaScript has a built-in Date object, which is a key tool for working with dates and times.

Have you ever visited a website (such as an e-commerce website) that displays items at a discounted price for a limited time? Or the opening countdown on the restaurant’s website? Or a timed animation on the website? These are some examples of the many scenarios for web development using date and time APIs.

Get the current date and time

Now how can we get the current date and time using the built-in Date object in JavaScript? this is very simple. All you need to do is create a new instance of the Date object without any parameters to get the current date and time. Next, log the current date and time to the console.

const currentDate = new Date();
console.log(currentDate);
Copy after login

This will log the current date and time to your console in the following format: Day-Month-Day-Year Hour-Minute-Second Time Zone. For example: Tue Jul 25 2023 12:37:10 GMT 0100 (West African Standard Time) .

Date The object also provides methods to extract various components of the date and time, such as year, month, day, hour, minutes, seconds, GMT, and time zone. Here is an example:

const currentDate = new Date();
const year = currentDate.getFullYear();
const month = currentDate.getMonth() + 1;
const hour = currentDate.getHours();
const minute = currentDate.getMinutes();
const timezoneOffsetHours = gmtOffsetInMinutes / -60;
const timezoneOffsetString = timezoneOffsetHours >= 0 ? `+${timezoneOffsetHours}` : `-${Math.abs(timezoneOffsetHours)}`;

console.log(`Year: ${year}`);
console.log(`Month: ${month}`);
console.log(`Hour: ${hour}`);
console.log(`Minute: ${minute}`);
console.log(`Timezone Offset: GMT${timezoneOffsetString}`);
Copy after login

This code creates a new Date object that contains the current date and time. Then it uses various methods of the Date object, such as getFullYear(), getMonth(), < /span>getHours() and getMinutes(), extract the various components of the date and time. We also did some calculations to get the time zone. When you run this code, you will see the current year, month, hour, minutes, and time zone on the console. Keep in mind that the results will depend on the current date and time of code execution.

Set the date and time format

Dates and times in JavaScript can also be formatted to suit specific needs. The Date object used above provides methods to extract the various components of a date and time and implement basic functionality. However, formatting dates and times to meet specific needs requires some additional steps. There are several JavaScript libraries available for formatting dates and times, including Moment.js, Luxon.js, Date-fns, Day.js, and others. In this section, we will learn about the Moment.js library.

To start using the Moment.js library, you need to include it in your project. You can do this using one of two methods:

  1. Install it using npm by entering the following command in the terminal or command line: <span>npm </span><span>install</span><span> moment</span>
  2. Link it from the CDN to your project. To link Moment.js to your project, add it to the head tag of your HTML file: <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment .min.js"></script>
const currentDate = new Date();
const formattedDateTime = moment(currentDate).format("YYYY-MM-DD HH:mm:ss");
console.log(formattedDateTime);
Copy after login

The output is 2023-07-25 13:04:38 (the date and time output is the time when I run the code). The format functions in Moment.js accept various format strings to customize the output as needed. In this example, we format it to display only the year, month, day, hour, minutes, and seconds.

Another example demonstrating the use of the Moment.js library is:

const addMinutes = moment().add(5, 'minutes');
console.log(`${addMinutes.format('h:mm a')}`);
const subtractDays = moment().subtract(3, 'days');
console.log(`${subtractDays.format('dddd, MMMM Do YYYY')}`)
Copy after login

Here’s what these lines of code do:

  • 第一行代码使用库中的 moment() 函数创建一个表示当前日期和时间的新 moment 对象。然后在此 moment 对象上调用 add() 方法,为其添加 5 分钟。传递给 add() 方法的第一个参数是要添加的单位数。传递的第二个参数是要添加的时间单位(在本例中为“分钟”)。
  • 第二行代码是将格式化的日期和时间记录到浏览器控制台的代码。在上一行创建的新 moment 对象上调用 format() 方法。它接受一个字符串作为参数来指定我们希望显示日期和时间的格式。在本例中,格式为:'h:mm a'。 “h”代表小时,“mm”代表 12 小时制格式的分钟,“a”代表 AM/PM 名称。例如,如果时间是 5:30,我们添加 5 分钟,那么时间将是 5:35。
  • 第三行代码与第一行非常相似,但它执行不同的操作。它使用库中的 moment() 函数创建一个表示当前日期和时间的新时刻对象。然后,在此 moment 对象上调用 subtract() 方法,从中减去 3 天。与 add() 方法一样,传递给 subtract() 方法的第一个参数是要减去的单位数。传递的第二个参数是要减去的时间单位(在本例中为“天”)。
  • 在第四行代码中,我们将格式化的日期和时间记录到控制台。在新创建的 moment 对象上调用 format() 方法,它接受一个字符串作为参数来指定我们要显示日期的格式。我们指定的格式是“dddd, MMMM Do YYYY”。 “dddd”代表完整的工作日名称,“MMMM”代表完整的月份名称,“Do”代表带后缀的月份中的日期,“YYYY”代表年份。假设当前日期是 2023 年 7 月 25 日,我们从中减去 3 天。日期将为“2023 年 7 月 22 日星期六”。

这是如何使用 Moment.js 在 JavaScript 中操作日期和时间的快速演示。

时区处理

正确处理时区对于与多个国家/地区的用户交互的应用至关重要。默认情况下,JavaScript 中的 Date 对象使用用户的系统时区。然而,它不提供对特定时区工作的直接支持。使用 ECMAScript 国际化 API (ECMA-402) 中的 Intl.DateTimeFormat 对象来有效管理时区。该格式允许您以本地化格式显示日期和时间信息,包括时区数据。

以下是如何显示特定时区的当前日期和时间的快速演示:

const date = new Date(Date.UTC(2023, 6, 25, 3, 0, 0));
console.log(new Intl.DateTimeFormat("en-US").format(date));
console.log(new Intl.DateTimeFormat("en-GB").format(date));
console.log(new Intl.DateTimeFormat('en-GB', { dateStyle: 'full', timeStyle: 'long', timeZone: 'long', timeZone: 'Australia/Sydney' }).format(date));
Copy after login
  • 第一行代码创建一个新的Date对象,名为date,表示日期和时间。
  • 在第二行代码中,我们使用 Intl.DateTimeFormat 对象将 date 格式化为美国英语语言环境。 format() 方法用于格式化日期对象,然后返回格式化日期的字符串表示形式。在美国英语区域设置中,格式为月-日-年顺序。因此输出将为 7/25/2023
  • 第三行代码也是如此,但在本例中,我们将 date 格式化为英式英语语言环境。格式为日-月-年顺序。因此输出将为 25/07/2023
  • 第四行使用 Intl.DateTimeFormat 对象,并提供以英式英语语言环境格式化 date 的选项,并将时区设置为“澳大利亚/悉尼”。 “dateStyle”选项设置为“full”,“timeStyle”选项设置为“long”。 “完整”日期样式提供日期的完整文本表示,“长”时间样式提供时间的长文本表示。 “timeZone”选项设置为“澳大利亚/悉尼”,这意味着日期和时间将以澳大利亚悉尼时区显示。

输出将如下所示:2023 年 7 月 25 日星期二 13:00:00 GMT+10。实际输出可能会因您当前的时区而异。

请注意,在上面的示例中,我们使用“6”代表七月,而不是“7”,后者代表月份位置。这是因为,在 JavaScript 中,Date 对象(以及 Intl.DateTimeFormat 对象)的月份参数是从零开始的,这意味着一月由 0 表示,二月由 1 表示,依此类推。因此,要表示 7 月,您应该使用 6 而不是 7,而对于 8 月,您应该使用 7 而不是 8。

执行日期和时间操作

JavaScript 中的 Date 对象提供了多种执行日期和时间操作的方法,例如计算两个日期之间的差异、添加或删除时间间隔以及比较日期。一些常用的方法有 getTime()setTime()getFullYear()getMonth()getDate()getHours()、phpcn cphpcn>getMinutes () 和 getSeconds()这些操作对于计算持续时间、设置截止日期和处理应用程序中与时间相关的逻辑等任务至关重要。

以下示例说明了如何计算两个日期之间的差异:

const startDate = new Date("2023-07-01");
const endDate = new Date("2023-07-17");
const timeDifference = endDate.getTime() - startDate.getTime();
const daysDifference = Math.floor(timeDifference / (1000 * 60 * 60 * 24));
console.log(`The days difference is: ${daysDifference}`);
Copy after login

代码说明

  • 第一行代码创建一个新的 Date 对象,表示日期 2023 年 7 月 1 日。Date 构造函数使用 和格式为“YYYY-MM-DD”的日期字符串来指定所需的开始时间日期。
  • 另一个新的 Date 对象表示日期 2023 年 7 月 17 日,也是使用指定格式的结束日期创建的。
  • 第三行代码是计算两个新创建的日期对象“endDate”和“startDate”之间的差异。 getTime()方法用于获取每个Date对象的时间值。通过从 endDate 时间值减去 startDate 时间值,我们得到两个日期之间的时间差(以毫秒为单位)。
  • 第四行代码:要计算两个日期之间的差异,请将“timeDifference”(以毫秒为单位)除以一天中的毫秒数,即 1000 毫秒乘以 60 秒乘以 60分钟乘以 24 小时。结果就是两个日期之间的天数差。 Math.floor() 函数用于将结果向下舍入到最接近的整数,以确保我们得到代表天数的整数。
  • 第五行代码将“daysDifference”记录到控制台。输出将是 startDateendDate 之间的天数。在此示例中,输出将为 The days Difference is: 16,表示 2023 年 7 月 1 日到 2023 年 7 月 17 日之间有 16 天。

总之,代码示例使用 Date 对象和简单的算术运算来计算两个提供的日期之间的天数差异(startDateendDate)。这对于许多与日期相关的计算非常有用,例如确定两个事件之间的持续时间或给定截止日期之前的天数。

结论

在本文中,我们探讨了在 JavaScript 中处理日期和时间的各个方面。我们讨论了如何执行常见的日期和时间计算,包括添加和减去时间间隔、比较日期以及计算日期之间的差异。我们还探索了流行的 Moment.js 库,它提供了处理日期和时间的附加功能。本文还向我们展示了如何使用 Intl.DateTimeFormat 对象格式化日期和时间。

最后,学习 JavaScript 中的日期和时间 API 使开发人员能够在各个领域创建功能强大、用户友好且对时间敏感的应用程序,从简单的时间显示到计时器倒计时,再到复杂的调度和事件处理。了解如何有效地使用日期和时间数据是任何 JavaScript 开发人员的必备技能,它可以显着提高应用程序的功能和可用性。

The above is the detailed content of Get the current date and time using JavaScript API to get the current date and time. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!