JavaScript 时间格式转换
在前端开发中,经常会涉及到处理时间的操作,如获取当前时间、格式化时间等。本文将介绍如何使用 JavaScript 进行时间格式的转换,包括时间戳转换为指定格式、日期字符串转换为指定格式等操作。让我们一起来学习吧!
1. 时间戳转换为指定格式
示例代码1:
// 时间戳转换为指定格式
function formatTimestamp(timestamp, format) {
let date = new Date(timestamp);
let year = date.getFullYear();
let month = (date.getMonth() + 1).toString().padStart(2, '0');
let day = date.getDate().toString().padStart(2, '0');
let hours = date.getHours().toString().padStart(2, '0');
let minutes = date.getMinutes().toString().padStart(2, '0');
let seconds = date.getSeconds().toString().padStart(2, '0');
return format.replace('YYYY', year)
.replace('MM', month)
.replace('DD', day)
.replace('HH', hours)
.replace('mm', minutes)
.replace('ss', seconds);
}
let timestamp = 1617272332536;
let formattedDate = formatTimestamp(timestamp, 'YYYY-MM-DD HH:mm:ss');
console.log(formattedDate); // 输出:2021-04-01 10:45:32
在上面的示例中,我们定义了一个函数 formatTimestamp
,用于将时间戳转换为指定格式的日期时间字符串。我们传入时间戳和指定的格式,然后将日期时间字符串中的年、月、日、时、分、秒进行替换。
2. 日期字符串转换为指定格式
示例代码2:
// 日期字符串转换为指定格式
function formatDateStr(dateStr, format) {
let date = new Date(dateStr);
let year = date.getFullYear();
let month = (date.getMonth() + 1).toString().padStart(2, '0');
let day = date.getDate().toString().padStart(2, '0');
let hours = date.getHours().toString().padStart(2, '0');
let minutes = date.getMinutes().toString().padStart(2, '0');
let seconds = date.getSeconds().toString().padStart(2, '0');
return format.replace('YYYY', year)
.replace('MM', month)
.replace('DD', day)
.replace('HH', hours)
.replace('mm', minutes)
.replace('ss', seconds);
}
let dateStr = '2021-04-01T10:45:32';
let formattedDate = formatDateStr(dateStr, 'YYYY年MM月DD日 HH时mm分ss秒');
console.log(formattedDate); // 输出:2021年04月01日 10时45分32秒
在上面的示例中,我们定义了一个函数 formatDateStr
,用于将日期字符串转换为指定格式的日期时间字符串。我们传入日期字符串和指定的格式,然后将日期时间字符串中的年、月、日、时、分、秒进行替换。
3. 获取当前时间并格式化
示例代码3:
// 获取当前时间并格式化
function getCurrentTime(format) {
let date = new Date();
let year = date.getFullYear();
let month = (date.getMonth() + 1).toString().padStart(2, '0');
let day = date.getDate().toString().padStart(2, '0');
let hours = date.getHours().toString().padStart(2, '0');
let minutes = date.getMinutes().toString().padStart(2, '0');
let seconds = date.getSeconds().toString().padStart(2, '0');
return format.replace('YYYY', year)
.replace('MM', month)
.replace('DD', day)
.replace('HH', hours)
.replace('mm', minutes)
.replace('ss', seconds);
}
let formattedDate = getCurrentTime('YYYY/MM/DD HH:mm:ss');
console.log(formattedDate); // 输出:2021/04/01 10:45:32
在上面的示例中,我们定义了一个函数 getCurrentTime
,用于获取当前时间并格式化为指定的日期时间字符串。我们获取当前时间的年、月、日、时、分、秒,并将其替换到指定格式的字符串中。
通过以上示例,我们学习了如何使用 JavaScript 进行时间格式的转换操作。