专业编程基础技术教程

网站首页 > 基础教程 正文

js日期及格式化

ccvgpt 2024-08-10 12:47:39 基础教程 9 ℃
function dateFormat(fmt, date) {
    let ret;
    const opt = {
        "Y+": date.getFullYear().toString(),        // 年
        "m+": (date.getMonth() + 1).toString(),     // 月
        "d+": date.getDate().toString(),            // 日
        "H+": date.getHours().toString(),           // 时
        "M+": date.getMinutes().toString(),         // 分
        "S+": date.getSeconds().toString()          // 秒
        // 有其他格式化字符需求可以继续添加,必须转化成字符串
    };
    for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
        };
    };
    return fmt;
}

let date = new Date()

dateFormat("YYYY-mm-dd HH:MM:SS", date)

js日期及格式化

console.log(dateFormat("YYYY-mm-dd HH:MM", date));

输出: 2019-06-06 19:45:35

Date.prototype.format = function(fmt){
  var o = {
    "M+" : this.getMonth()+1,                 //月份
    "d+" : this.getDate(),                    //日
    "h+" : this.getHours(),                   //小时
    "m+" : this.getMinutes(),                 //分
    "s+" : this.getSeconds(),                 //秒
    "q+" : Math.floor((this.getMonth()+3)/3), //季度
    "S"  : this.getMilliseconds()             //毫秒
  };
  if(/(y+)/.test(fmt)){
    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
  }
  for(var k in o){
    if(new RegExp("("+ k +")").test(fmt)){
      fmt = fmt.replace(
        RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));  
    }       
  }
  return fmt;
}

var now = new Date();

var nowStr = now.format("yyyy-MM-dd hh:mm:ss");

//2021-06-03 19:17:35

console.log(nowStr);

//2021年06月03日

console.log(new Date().format("yyyy年MM月dd日"));

var nowStr = now.format("yyyy-MM-dd hh:mm:ss");

//2021-06-03 19:17:35

console.log(nowStr);//

//2021年06月03日19小时17分35秒

console.log(new Date().format("yyyy年MM月dd日hh小时mm分ss秒"));

//输出:

2021-06-03 19:17:35

2021年06月03日

2021-06-03 19:17:35

2021年06月03日19小时17分35秒

常用api

let date = new Date();
    console.log(date.getFullYear()); //当前日期的年 2022
    console.log(date.getMonth() + 1); //月份+1 由于月份是0-11计算 所以需要 +1 
    console.log(date.getDate()); // 日
    console.log(date.getDay()); // 星期几  注意:星期日返回的是0
    console.log(date.getHours()); // 时
    console.log(date.getMinutes()); // 分
    console.log(date.getSeconds()); // 秒

toLocaleString(原生方法)

let timer = new Date()
    console.log(timer.toLocaleString()) // 日期+时间 2024/5/08 23:07:35
    console.log(timer.toLocaleDateString()) // 日期 2024/5/08 
    console.log(timer.toLocaleTimeString()) // 时间 23:10:31 
console.log(time.getFullYear().toString().padStart(4, '0')) // 年 2023
  console.log((time.getMonth() + 1).toString().padStart(2, '0')) // 月 05
  console.log(time.getDate().toString().padStart(2, '0')) // 日 29
  console.log('星期' + (time.getDay() === 0 ? 7 : time.getDay())) // 周 星期1
  console.log(time.getHours().toString().padStart(2, '0')) // 时 01
  console.log(time.getMinutes().toString().padStart(2, '0')) // 分 19
  console.log(time.getSeconds().toString().padStart(2, '0')) // 秒 55
let time = new Date()
    // 定义格式化封装函数
    function formaData(timer) {
        const year = timer.getFullYear()
        const month = timer.getMonth() + 1 // 由于月份从0开始,因此需加1
        const day = timer.getDate()
        const hour = timer.getHours()
        const minute = timer.getMinutes()
        const second = timer.getSeconds()
        return `${pad(year, 4)}-${pad(month)}-${pad(day)} ${pad(hour)}:${pad(minute)}:${pad(second)}`
    }
    // 定义具体处理标准
    // timeEl 传递过来具体的数值:年月日时分秒
    // total 字符串总长度 默认值为2
    // str 补充元素 默认值为"0"
    function pad(timeEl, total = 2, str = '0') {
        return timeEl.toString().padStart(total, str)
    }
    // 调用函数
    console.log(formaData(time)) // 2023-05-29 00:30:19

第三方库

npm install moment
import moment from 'moment';
    Vue.prototype.$moment = moment
// `this.$moment()` 输出当前时间的moment对象
console.log(this.$moment().format('YYYY-MM-DD HH:mm:ss')); // 2023-05-29 00:30:19
let date = new Date();
// 写法一
console.log(date.valueOf()); //现在时间距离1970.1.1的毫秒数
console.log(date.getTime());

// 写法二
let date = +new Date(); 
console.log(date); //返回当前总的毫秒数

// 写法三
 console.log(Date.now()); // H5新增 低版本浏览器打不开

Tags:

最近发表
标签列表