喔唷网 - 网络从业者技术信息综合门户!

当前位置: 主页 > 教程技术 > 编程语言 > javascript

JS获取时间以及操作时间的各类详细案例

时间 : 2025-04-21 17:18来源 : 喔唷网作者 : 喔唷教程点击 :
javascript对时间的控制相对比较简单,而且使用率相当高,不经可以获取到时间计算时间、格式化时间、字符串对时间的转换还可以对时间的时区进行控制和修改,并且能够获得到相对时间。

JavaScript 提供了丰富的日期时间处理功能,主要通过 Date 对象实现各种时间操作。本文总结了常见的时间转换场景,包括获取当前时间、时间戳与日期对象互转、日期格式化、字符串解析、时间计算、时区转换、相对时间显示等核心功能。对于简单需求,可以使用原生 Date 对象配合基本方法实现;复杂场景下,推荐使用 day.js 或 date-fns 等现代日期库,它们提供了更简洁的 API 和更强大的功能。时间处理的关键点包括:正确处理时区问题、注意月份从 0 开始计数、使用 padStart 补零确保格式统一,以及使用 getTime() 进行精确的时间计算。掌握这些时间转换技巧,能够高效解决开发中的各种时间处理需求。

以下是一些常见的 JavaScript 时间转换代码示例:

1、通过js获取当前时间

// 获取当前时间戳(毫秒)
const timestamp = Date.now();

// 获取当前时间对象
const now = new Date();

2、时间戳与日期对象转换

// 时间戳转Date对象
const timestamp = 1625097600000;
const date = new Date(timestamp);

// Date对象转时间戳
const timestamp = new Date().getTime();
// 或者
const timestamp = +new Date();

3、格式化日期的用法

// 简单格式化
function formatDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

// 复杂格式化
function formatDateTime(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 使用
console.log(formatDate(new Date())); // 2023-05-15
console.log(formatDateTime(new Date())); // 2023-05-15 14:30:45

4、字符串转换为日期

// ISO格式字符串转Date
const date1 = new Date('2023-05-15T14:30:00Z');

// 自定义格式字符串转Date
function parseDate(dateString) {
  const parts = dateString.split('-');
  return new Date(parts[0], parts[1] - 1, parts[2]);
}

const date2 = parseDate('2023-05-15');

5、js对时间的计算

// 添加天数
function addDays(date, days) {
  const result = new Date(date);
  result.setDate(result.getDate() + days);
  return result;
}

// 添加小时
function addHours(date, hours) {
  const result = new Date(date);
  result.setTime(result.getTime() + (hours * 60 * 60 * 1000));
  return result;
}

// 计算两个日期之间的天数差
function dayDiff(date1, date2) {
  const diffTime = Math.abs(date2 - date1);
  return Math.floor(diffTime / (1000 * 60 * 60 * 24));
}

6、时区转换

// 本地时间转UTC
function localToUTC(date) {
  return new Date(date.getTime() + date.getTimezoneOffset() * 60000);
}

// UTC转本地时间
function utcToLocal(date) {
  return new Date(date.getTime() - date.getTimezoneOffset() * 60000);
}

// 转换为特定时区时间
function convertToTimeZone(date, timeZone) {
  return new Date(date.toLocaleString('en-US', { timeZone }));
}

7、相对时间的显示

function timeAgo(date) {
  const seconds = Math.floor((new Date() - date) / 1000);

  let interval = Math.floor(seconds / 31536000);
  if (interval >= 1) return interval + "年前";

  interval = Math.floor(seconds / 2592000);
  if (interval >= 1) return interval + "个月前";

  interval = Math.floor(seconds / 86400);
  if (interval >= 1) return interval + "天前";

  interval = Math.floor(seconds / 3600);
  if (interval >= 1) return interval + "小时前";

  interval = Math.floor(seconds / 60);
  if (interval >= 1) return interval + "分钟前";

  return Math.floor(seconds) + "秒前";
}

// 使用
console.log(timeAgo(new Date(Date.now() - 5000))); // 5秒前

8、通过js获取特定时间

// 获取当天的开始时间
function getDayStart() {
  const date = new Date();
  date.setHours(0, 0, 0, 0);
  return date;
}

// 获取当月的第一天
function getMonthStart() {
  const date = new Date();
  date.setDate(1);
  date.setHours(0, 0, 0, 0);
  return date;
}

// 获取今年的第一天
function getYearStart() {
  const date = new Date();
  date.setMonth(0, 1);
  date.setHours(0, 0, 0, 0);
  return date;
}

9、验证时间的有效性

function isValidDate(date) {
  return date instanceof Date && !isNaN(date);
}

// 使用
console.log(isValidDate(new Date())); // true
console.log(isValidDate(new Date('invalid'))); // false


栏目列表

关联类容

热点推荐

栏目推荐

猜你喜欢