分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 运营维护

js 关于时间方面的通用函数(时间格式化,分钟数转换为小时+分钟,计算天数差的函数)

发布时间:2023-09-06 02:22责任编辑:蔡小小关键词:js

项目中经常需要把数据转换,把经常用到的做过总结:

一、时间格式化

export function formatDate (date, fmt) { ?if (/(y+)/.test(fmt)) { ???fmt = fmt.replace(RegExp.$1, (date.getFullYear() + ‘‘).substr(4 - RegExp.$1.length)) ?} ?let o = { ???‘M+‘: date.getMonth() + 1, ???‘d+‘: date.getDate(), ???‘h+‘: date.getHours(), ???‘m+‘: date.getMinutes(), ???‘s+‘: date.getSeconds() ?} ?for (let k in o) { ???if (new RegExp(`(${k})`).test(fmt)) { ?????let str = o[k] + ‘‘ ?????fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : (‘00‘ + str).substr(str.length)) ???} ?} ?return fmt}

 

二、分钟数转换为小时+分钟

export function changeHourMinutestr (str) { ?let hours = Math.floor(str / 60).toString() ?let minutes = (str % 60).toString() ?if (str !== ‘0‘ && str !== ‘‘ && str !== null) { ???return hours + ‘时‘ + (minutes.length < 2 ? ‘0‘ + minutes : minutes) + ‘分‘ ?} else { ???return ‘‘ ?}}

三、计算天数差的函数

 export function ?getDateDiff(start, ?end){ ???????if (!end) { ?????return ‘借阅中‘ ???} ???let ?aDate, ?oDate1, ?oDate2, ?iDays ?????aDate ?= ?start.split("-") ?????oDate1 ?= ?new ?Date(aDate[0] ?+ ?‘/‘ ?+ ?aDate[1] ?+ ?‘/‘ ?+ ?aDate[2]) ???//转换为2016/12/18格式 ?????aDate ?= ?end.split("-") ?????oDate2 ?= ?new ?Date(aDate[0] ?+ ?‘/‘ ?+ ?aDate[1] ?+ ?‘/‘ ?+ ?aDate[2]) ?????iDays ?= ?Math.ceil(Math.abs(oDate1 ?- ?oDate2) ?/ ?1000 ?/ ?60 ?/ ?60 ?/24) ???//把相差的毫秒数转换为天数 ?????return ?iDays ???} 

 

  

js 关于时间方面的通用函数(时间格式化,分钟数转换为小时+分钟,计算天数差的函数)

原文地址:https://www.cnblogs.com/wangdashi/p/9964911.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved