日期时间处理 #
JavaScript Date 对象 #
JavaScript 的 Date 对象用于处理日期和时间。
text
┌─────────────────────────────────────────────────────────────┐
│ Date 对象创建方式 │
├─────────────────────────────────────────────────────────────┤
│ new Date() 当前时间 │
│ new Date(timestamp) 时间戳 │
│ new Date(dateString) 日期字符串 │
│ new Date(year, month, day, hours, minutes, seconds) │
└─────────────────────────────────────────────────────────────┘
创建日期 #
javascript
const now = new Date();
console.log(now);
const fromTimestamp = new Date(1712208000000);
console.log(fromTimestamp);
const fromString = new Date('2026-04-04T12:00:00');
console.log(fromString);
const fromParts = new Date(2026, 3, 4, 12, 0, 0);
console.log(fromParts);
基础函数 #
formater(time, format) #
格式化日期时间。
javascript
const _toString = val => Object.prototype.toString.call(val).slice(8, -1);
const isString = val => _toString(val) === 'String';
const isNumber = val => _toString(val) === 'Number';
const isDate = val => _toString(val) === 'Date';
const addZero = (num) => num > 9 ? num : ('0' + num);
export const getTimeInfo = (time) => {
let dateTime = getRealTime(time);
if (!dateTime) return null;
const year = dateTime.getFullYear();
const month = dateTime.getMonth() + 1;
const day = dateTime.getDate();
const hours = dateTime.getHours();
const minutes = dateTime.getMinutes();
const seconds = dateTime.getSeconds();
return {
yyyy: year,
MM: addZero(month),
dd: addZero(day),
hh: addZero(hours % 12),
mm: addZero(minutes),
ss: addZero(seconds),
HH: addZero(hours)
};
};
export const formater = (time, format = '') => {
const timeInfo = getTimeInfo(time);
if (!timeInfo) return '';
const { yyyy, MM, dd, hh, mm, ss, HH } = timeInfo;
return format
.replace(/yyyy/, yyyy)
.replace(/MM/, MM)
.replace(/dd/, dd)
.replace(/HH/, HH)
.replace(/hh/, hh)
.replace(/mm/, mm)
.replace(/ss/, ss);
};
使用示例 #
javascript
import { formater } from './utils/date';
const now = Date.now();
console.log(formater(now, 'yyyy-MM-dd'));
console.log(formater(now, 'yyyy/MM/dd'));
console.log(formater(now, 'yyyy-MM-dd HH:mm:ss'));
console.log(formater(now, 'MM月dd日 HH:mm'));
console.log(formater(now, 'hh:mm:ss'));
formater('1712208000000', 'yyyy-MM-dd');
formater(new Date(), 'yyyy-MM-dd');
getTimeSpan(time1, time2, format) #
计算两个时间的间隔。
javascript
const onesecond = 1000;
const oneminute = 60 * onesecond;
const onehour = 60 * oneminute;
const oneday = 24 * onehour;
export const getTimeSpan = (time1, time2, format = 's') => {
const dateTime1 = getRealTime(time1);
const dateTime2 = getRealTime(time2);
const timespan = Math.abs(dateTime1.getTime() - dateTime2.getTime());
let den = onesecond;
switch (format) {
case 's': den = onesecond; break;
case 'm': den = oneminute; break;
case 'h': den = onehour; break;
case 'd': den = oneday; break;
}
return Math.ceil(timespan / den);
};
使用示例 #
javascript
import { getTimeSpan } from './utils/date';
const date1 = new Date('2026-04-01');
const date2 = new Date('2026-04-04');
console.log(getTimeSpan(date1, date2, 's'));
console.log(getTimeSpan(date1, date2, 'm'));
console.log(getTimeSpan(date1, date2, 'h'));
console.log(getTimeSpan(date1, date2, 'd'));
const start = new Date('2026-04-04 09:00:00');
const end = new Date('2026-04-04 18:00:00');
console.log(`工作时长: ${getTimeSpan(start, end, 'h')} 小时`);
getTimeInfo(time) #
获取时间的各个部分。
javascript
import { getTimeInfo } from './utils/date';
const info = getTimeInfo(Date.now());
console.log(info);
进阶用法 #
相对时间 #
javascript
const getRelativeTime = (time) => {
const now = Date.now();
const diff = now - new Date(time).getTime();
const minute = 60 * 1000;
const hour = 60 * minute;
const day = 24 * hour;
const week = 7 * day;
const month = 30 * day;
const year = 365 * day;
if (diff < minute) {
return '刚刚';
} else if (diff < hour) {
return `${Math.floor(diff / minute)} 分钟前`;
} else if (diff < day) {
return `${Math.floor(diff / hour)} 小时前`;
} else if (diff < week) {
return `${Math.floor(diff / day)} 天前`;
} else if (diff < month) {
return `${Math.floor(diff / week)} 周前`;
} else if (diff < year) {
return `${Math.floor(diff / month)} 个月前`;
} else {
return `${Math.floor(diff / year)} 年前`;
}
};
getRelativeTime(Date.now() - 5000);
getRelativeTime(Date.now() - 5 * 60 * 1000);
getRelativeTime(Date.now() - 5 * 60 * 60 * 1000);
getRelativeTime(Date.now() - 5 * 24 * 60 * 60 * 1000);
倒计时 #
javascript
class Countdown {
constructor(endTime, onUpdate, onComplete) {
this.endTime = new Date(endTime).getTime();
this.onUpdate = onUpdate;
this.onComplete = onComplete;
this.timer = null;
}
start() {
this.update();
this.timer = setInterval(() => this.update(), 1000);
}
stop() {
if (this.timer) {
clearInterval(this.timer);
this.timer = null;
}
}
update() {
const now = Date.now();
const diff = this.endTime - now;
if (diff <= 0) {
this.stop();
this.onComplete && this.onComplete();
return;
}
const days = Math.floor(diff / (24 * 60 * 60 * 1000));
const hours = Math.floor((diff % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000));
const minutes = Math.floor((diff % (60 * 60 * 1000)) / (60 * 1000));
const seconds = Math.floor((diff % (60 * 1000)) / 1000);
this.onUpdate && this.onUpdate({ days, hours, minutes, seconds });
}
}
const countdown = new Countdown(
Date.now() + 10 * 60 * 1000,
(time) => console.log(`${time.minutes}:${time.seconds}`),
() => console.log('倒计时结束')
);
countdown.start();
日期计算 #
javascript
const addDays = (date, days) => {
const result = new Date(date);
result.setDate(result.getDate() + days);
return result;
};
const addMonths = (date, months) => {
const result = new Date(date);
result.setMonth(result.getMonth() + months);
return result;
};
const addYears = (date, years) => {
const result = new Date(date);
result.setFullYear(result.getFullYear() + years);
return result;
};
const today = new Date();
console.log(addDays(today, 7));
console.log(addMonths(today, 1));
console.log(addYears(today, 1));
获取特定日期 #
javascript
const getStartOfDay = (date = new Date()) => {
const result = new Date(date);
result.setHours(0, 0, 0, 0);
return result;
};
const getEndOfDay = (date = new Date()) => {
const result = new Date(date);
result.setHours(23, 59, 59, 999);
return result;
};
const getStartOfWeek = (date = new Date()) => {
const result = new Date(date);
const day = result.getDay();
result.setDate(result.getDate() - day);
result.setHours(0, 0, 0, 0);
return result;
};
const getStartOfMonth = (date = new Date()) => {
const result = new Date(date);
result.setDate(1);
result.setHours(0, 0, 0, 0);
return result;
};
const getEndOfMonth = (date = new Date()) => {
const result = new Date(date);
result.setMonth(result.getMonth() + 1);
result.setDate(0);
result.setHours(23, 59, 59, 999);
return result;
};
console.log(getStartOfDay());
console.log(getEndOfDay());
console.log(getStartOfWeek());
console.log(getStartOfMonth());
console.log(getEndOfMonth());
判断日期 #
javascript
const isToday = (date) => {
const today = new Date();
const d = new Date(date);
return d.toDateString() === today.toDateString();
};
const isYesterday = (date) => {
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
const d = new Date(date);
return d.toDateString() === yesterday.toDateString();
};
const isTomorrow = (date) => {
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
const d = new Date(date);
return d.toDateString() === tomorrow.toDateString();
};
const isWeekend = (date) => {
const d = new Date(date);
const day = d.getDay();
return day === 0 || day === 6;
};
const isLeapYear = (year) => {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
};
console.log(isToday(new Date()));
console.log(isWeekend(new Date()));
console.log(isLeapYear(2024));
时区处理 #
获取时区信息 #
javascript
const getTimezoneInfo = () => {
const date = new Date();
return {
offset: date.getTimezoneOffset(),
offsetHours: -date.getTimezoneOffset() / 60,
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
isDST: date.getTimezoneOffset() !== new Date(date.getFullYear(), 0).getTimezoneOffset()
};
};
console.log(getTimezoneInfo());
时区转换 #
javascript
const convertTimezone = (date, fromOffset, toOffset) => {
const d = new Date(date);
const diff = (toOffset - fromOffset) * 60 * 60 * 1000;
return new Date(d.getTime() + diff);
};
const toLocalTime = (utcDate) => {
return new Date(utcDate);
};
const toUTC = (localDate) => {
const d = new Date(localDate);
return new Date(d.getTime() + d.getTimezoneOffset() * 60 * 1000);
};
格式化为指定时区 #
javascript
const formatWithTimezone = (date, timezone, format = 'yyyy-MM-dd HH:mm:ss') => {
const options = {
timeZone: timezone,
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false
};
const formatter = new Intl.DateTimeFormat('en-US', options);
const parts = formatter.formatToParts(new Date(date));
const values = {};
parts.forEach(({ type, value }) => {
if (type === 'year') values.yyyy = value;
if (type === 'month') values.MM = value;
if (type === 'day') values.dd = value;
if (type === 'hour') values.HH = value;
if (type === 'minute') values.mm = value;
if (type === 'second') values.ss = value;
});
return format
.replace('yyyy', values.yyyy)
.replace('MM', values.MM)
.replace('dd', values.dd)
.replace('HH', values.HH)
.replace('mm', values.mm)
.replace('ss', values.ss);
};
formatWithTimezone(new Date(), 'America/New_York');
formatWithTimezone(new Date(), 'Asia/Tokyo');
formatWithTimezone(new Date(), 'Europe/London');
实际应用场景 #
1. 日历组件 #
javascript
const getCalendarDays = (year, month) => {
const firstDay = new Date(year, month, 1);
const lastDay = new Date(year, month + 1, 0);
const days = [];
const startPadding = firstDay.getDay();
for (let i = startPadding - 1; i >= 0; i--) {
const date = new Date(year, month, -i);
days.push({ date, isCurrentMonth: false });
}
for (let i = 1; i <= lastDay.getDate(); i++) {
const date = new Date(year, month, i);
days.push({ date, isCurrentMonth: true });
}
const endPadding = 6 - lastDay.getDay();
for (let i = 1; i <= endPadding; i++) {
const date = new Date(year, month + 1, i);
days.push({ date, isCurrentMonth: false });
}
return days;
};
getCalendarDays(2026, 3);
2. 时间范围选择 #
javascript
const getDateRange = (type) => {
const now = new Date();
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
switch (type) {
case 'today':
return { start: today, end: now };
case 'yesterday':
const yesterday = new Date(today);
yesterday.setDate(yesterday.getDate() - 1);
return { start: yesterday, end: today };
case 'thisWeek':
const weekStart = new Date(today);
weekStart.setDate(weekStart.getDate() - weekStart.getDay());
return { start: weekStart, end: now };
case 'thisMonth':
const monthStart = new Date(today.getFullYear(), today.getMonth(), 1);
return { start: monthStart, end: now };
case 'last7Days':
const last7 = new Date(today);
last7.setDate(last7.getDate() - 7);
return { start: last7, end: now };
case 'last30Days':
const last30 = new Date(today);
last30.setDate(last30.getDate() - 30);
return { start: last30, end: now };
}
};
console.log(getDateRange('today'));
console.log(getDateRange('thisWeek'));
console.log(getDateRange('last7Days'));
3. 工作日计算 #
javascript
const getWorkdays = (startDate, endDate) => {
let count = 0;
const current = new Date(startDate);
const end = new Date(endDate);
while (current <= end) {
const day = current.getDay();
if (day !== 0 && day !== 6) {
count++;
}
current.setDate(current.getDate() + 1);
}
return count;
};
const addWorkdays = (date, days) => {
const result = new Date(date);
let remaining = days;
while (remaining > 0) {
result.setDate(result.getDate() + 1);
const day = result.getDay();
if (day !== 0 && day !== 6) {
remaining--;
}
}
return result;
};
console.log(getWorkdays('2026-04-01', '2026-04-30'));
console.log(addWorkdays('2026-04-01', 5));
下一步 #
现在你已经掌握了日期时间处理,接下来学习 本地存储,了解浏览器本地数据存储!
最后更新:2026-04-04