js获取当前年月日 时分秒的方法(new Date/)

时间:2025-04-01 08:42:42

一、new Date():

export let getDate = () => {
    // 补零
    let addZero = (t) => {
        return t < 10 ? '0' + t : t;
    }
    let time = new Date();
    let Y = (), // 年
        M = () + 1, // 月
        D = (), // 日
        h = (), // 时
        m = (), // 分
        s = (); // 秒
    if (M > 12) {
        // 注: new Date()的年月日的拼接,在月份为12月时,会出现 获取月份+1 后,为13月的bug,需要特殊处理。用moment第三方插件获取时间也可避免此问题。
        M = M - 12;
    }
    return `${Y}-${addZero(M)}-${addZero(D)} ${addZero(h)}:${addZero(m)}:${addZero(s)}`;
}
// 调用
import { getDate } from "./utils/";
getDate(); // 2024-03-31 09:34:31

二、:

//  下载:
npm i moment
或
yarn add moment
// 引入
import moment from "moment";
// 使用
moment().format('YYYY-MM-DD HH:mm:ss'); // 获取当前时间:2024-03-31 09:38:02
moment().startOf('day').format('YYYY-MM-DD HH:mm:ss'); // 获取今天0时0分0秒:2024-03-31 00:00:00
moment().endOf('day').format('YYYY-MM-DD HH:mm:ss'); // 获取今天23时59分59秒:2024-03-31 23:59:59
moment().daysInMonth(); // 获取当月的总天数:31
moment().valueOf(); // 获取时间戳:1711849082142
moment().add(-1, 'y').format('YYYY'); // 上一年:2023
moment().add(0, 'y').format('YYYY'); // 今年:2024
moment().add(1, 'y').format('YYYY'); // 下一年:2025