Skip to content

时间和日期

获取现在的时间

js
// 以Date形式存储
var now = new Date();
// 获取当前的年份
var year = now.getFullYear();
// 获取当前的月份(注意:返回的月份是从0开始的,所以要加1)
var month = now.getMonth() + 1;
// 获取当前是几号
var day = now.getDate();
// 获取当前小时
var hours = now.getHours();
// 获取当前分钟
var minutes = now.getMinutes();
// 获取当前秒数
var seconds = now.getSeconds();
// 获取当前毫秒数
var milliseconds = now.getMilliseconds();

格式化时间或日期

使用day.js格式化时间或日期

day.js的官方文档在这里

安装day.js

  • 使用yarn或者npm安装
    bash
    npm install dayjs
    # 或者使用yarn
    yarn add dayjs
  • 这样导入js
    js
    const dayjs = require('dayjs');
    // 对于新版本的ES,这样导入
    import dayjs from 'dayjs';
js
import dayjs from 'dayjs'

const dateNow=new Date();
console.log(dayjs(dateNow).format("YYYY-MM-DD hh:mm"))
// 输出当前的时间,例如2024-4-8 19:02

详细的格式化文档见这里

计算时间

计算距离多长时间之前(之后)的时间

js
var nowTime=new Date();
// 注意时间间隔以毫秒计算,下面为一天的毫秒数
var millisecondsToAdd = 1000 * 60 * 60 * 24;
// 注意讲Date转换成时间戳再进行运算
var newTime=new Date(nowTime.getTime() + millisecondsToAdd);

计算两个时间之间的时间差

js
// 创建两个表示时间的 Date 对象
var date1 = new Date('2024-04-01T12:00:00');
var date2 = new Date('2024-04-01T14:30:00');

// 计算两个时间之间的毫秒差,Date可以直接计算
var timeDifferenceInMilliseconds = Math.abs(date2 - date1);

// 计算毫秒差对应的小时数、分钟数和秒数
var hoursDifference = Math.floor(timeDifferenceInMilliseconds / (1000 * 60 * 60));
var minutesDifference = Math.floor((timeDifferenceInMilliseconds % (1000 * 60 * 60)) / (1000 * 60));
var secondsDifference = Math.floor((timeDifferenceInMilliseconds % (1000 * 60)) / 1000);

console.log("时间差为:" + hoursDifference + "小时 " + minutesDifference + "分钟 " + secondsDifference + "秒");

Released under the MIT License.