赞
踩
在编写JavaScript代码时,遇到需要获取当前日期和时间并将其格式化为 yyyymmddhhmmss 字符串的情况。可以使用本文中介绍的几种实现方式中的任意一种。
使用 Date 对象来获取当前日期和时间。
- const now = new Date();
-
- const year = now.getFullYear();
- const month = ('0' + (now.getMonth() + 1)).slice(-2);
- const day = ('0' + now.getDate()).slice(-2);
- const hours = ('0' + now.getHours()).slice(-2);
- const minutes = ('0' + now.getMinutes()).slice(-2);
- const seconds = ('0' + now.getSeconds()).slice(-2);
-
- const formattedTime = year + month + day + hours + minutes + seconds;
-
-
- console.log(formattedTime);
在上面的代码中,使用了 getFullYear、getMonth、getDate、getHours、getMinutes 和 getSeconds 函数来获取年、月、日、小时、分钟和秒。然后,使用 slice 函数将所有这些值转换为两位数字并将它们连接到一个字符串中。
Moment.js是一个流行的JavaScript日期库,它提供了许多日期和时间操作方法。
- const moment = require('moment');
-
- const formattedTime = moment().format('YYYYMMDDHHmmss');
-
- console.log(formattedTime);
无,笔者使用时没有运行成功
在上面的代码中,使用了moment.js库的format函数将当前时间格式化为 yyyymmddhhmmss 的字符串。
Intl.DateTimeFormat是一个内置的JavaScript日期库,它提供了本地化和格式化日期的方法。
- const options = { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false };
- const formattedTime = new Intl.DateTimeFormat('en-US', options).format(new Date()).replace(/[^0-9]/g, '');
-
- console.log(formattedTime);
在上面的代码中,使用了Intl.DateTimeFormat来格式化当前时间,并使用正则表达式将所有非数字字符替换为空字符串,以生成 yyyymmddhhmmss 的字符串。
day.js是一个轻量级的JavaScript日期库,它提供了许多日期和时间操作方法。
- const dayjs = require('dayjs');
-
- const formattedTime = dayjs().format('YYYYMMDDHHmmss');
-
- console.log(formattedTime);
无,笔者使用时没有运行成功
在上面的代码中,使用了day.js库的format函数将当前时间格式化为 yyyymmddhhmmss 的字符串。
在JavaScript中,可以使用 toLocaleString 函数来获取本地化的日期和时间。
- const now = new Date();
- const formattedTime = now.toLocaleString('en-US', {year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit'}).replace(/[^\d]/g, '');
-
- console.log(formattedTime);
在上面的代码中,使用了 toLocaleString 函数获取本地化的日期和时间,并使用正则表达式将所有非数字字符替换为空字符串,以生成 yyyymmddhhmmss 的字符串。
在JavaScript中,我们可以使用 padStart 函数来将数字字符串填充到指定的长度。
- const now = new Date();
- const year = now.getFullYear();
- const month = String(now.getMonth() + 1).padStart(2, '0');
- const day = String(now.getDate()).padStart(2, '0');
- const hours = String(now.getHours()).padStart(2, '0');
- const minutes = String(now.getMinutes()).padStart(2, '0');
- const seconds = String(now.getSeconds()).padStart(2, '0');
-
- const formattedTime = year + month + day + hours + minutes + seconds;
-
- console.log(formattedTime);
在上面的代码中,使用 padStart 函数将所有数字字符串填充到两位,并将它们连接到一个字符串中,以生成 yyyymmddhhmmss 的字符串。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。