Skip to content
On this page

dateFormat 日期格式化

Code
ts
function dateFormat(time: number | string | Date = Date.now(), fmt = "yyyy-MM-dd hh:mm:ss") {
  let date = new Date(time)
  let o = <any>{
    "M+": date.getMonth() + 1, //月份
    "d+": date.getDate(), //日
    "h+": date.getHours(), //小时
    "m+": date.getMinutes(), //分
    "s+": date.getSeconds(), //秒
    "q+": Math.floor((date.getMonth() + 3) / 3), //季度
    S: date.getMilliseconds(), //毫秒
  }
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length))
  for (let 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
}

基本使用

格式化时间戳


2023-06-27 11:41:45

vue
<script setup lang="ts">
import { dateFormat } from "@jqw755/q-ui"

dateFormat(1687837305000)
</script>

格式化字符串


2023/06/27

vue
<script setup lang="ts">
import { dateFormat } from "@jqw755/q-ui"

dateFormat(new Date(), "YYYY/MM/DD")
</script>

APIs

参数说明类型默认值必传
time时间戳;或者可以转化为 Date 类型的字符串日期;或者 Date 对象number | string | DateDate.now()false
format格式化目标形式string'YYYY-MM-DD HH:mm:ss'false

format 支持的格式化占位符列表

标识示例描述
YYYY2023年,四位数
M1-12月,从 1 开始
MM01-12月,两位数
D1-31
DD01-31日,两位数
H0-23小时
HH00-23小时,两位数
m0-59分钟
mm00-59分钟,两位数
s0-59
ss00-59秒,两位数

License