怎么把日期转换成这种格式"2024-03-22T00:00:00+08:00"
function formatDateToISO(date, timeZone) {
// 创建一个新的Date对象
let d = new Date(date);
// 获取本地时间字符串并格式化为ISO 8601格式
let options = { timeZone: timeZone, hour12: false };
let localDate = new Intl.DateTimeFormat('sv-SE', options).format(d);
let localTime = new Intl.DateTimeFormat('sv-SE', { ...options, hour: '2-digit', minute: '2-digit', second: '2-digit' }).format(d);
// 拼接日期和时间
let localISOTime = `${localDate}T${localTime}`;
// 获取时区偏移
let offset = d.getTimezoneOffset();
let sign = offset > 0 ? '-' : '+';
offset = Math.abs(offset);
let hours = String(Math.floor(offset / 60)).padStart(2, '0');
let minutes = String(offset % 60).padStart(2, '0');
return `${localISOTime}${sign}${hours}:${minutes}`;
}
// 示例使用
let date = new Date('2024-03-22T00:00:00');
console.log(formatDateToISO(date, 'Asia/Shanghai')); // 输出: 2024-03-22T00:00:00+08:00
8 回答4.7k 阅读✓ 已解决
6 回答3.4k 阅读✓ 已解决
6 回答2.3k 阅读
5 回答6.3k 阅读✓ 已解决
3 回答2.4k 阅读✓ 已解决
3 回答2.1k 阅读✓ 已解决
3 回答2.5k 阅读✓ 已解决
function formatDate(date, timezoneOffset = '+08:00') {
const padZero = (num) => (num < 10 ? '0' + num : num);
const year = date.getFullYear();
const month = padZero(date.getMonth() + 1);
const day = padZero(date.getDate());
const hours = padZero(date.getHours());
const minutes = padZero(date.getMinutes());
const seconds = padZero(date.getSeconds());
return
${year}-${month}-${day}T${hours}:${minutes}:${seconds}${timezoneOffset}
;}
const date = new Date('2024-03-22');
console.log(formatDate(date));
或者用moment.js
npm install moment
const moment = require('moment-timezone');
function formatDateWithMoment(date, timezone = 'Asia/Shanghai') {
return moment(date).tz(timezone).format('YYYY-MM-DD[T]HH:mm:ssZ');
}
const date = new Date('2024-03-22');
console.log(formatDateWithMoment(date));