Resolución de problemas de marca de tiempo de Javascript para formato de fecha y zona horaria del navegador

// 时间(可传入时间戳或时间对象), 格式,时区,默认北京时区为东8
export function parseTime (time, cFormat, zone = 8) {
    
    
  if (arguments.length === 0) {
    
    
    return null
  }
  const format = cFormat || '{
    
    y}-{
    
    m}-{
    
    d} {
    
    h}:{
    
    i}:{
    
    s}'
  let date
  if (typeof time === 'object') {
    
    
    date = time
  } else {
    
    
    if (('' + time).length === 10) time = parseInt(time) * 1000
    date = new Date(time)
  }
  // 时区调整
  const utc = time + new Date(time).getTimezoneOffset() * 60000
  const wishTime = utc + (3600000 * zone)
  date = new Date(wishTime)
  const formatObj = {
    
    
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const timeStr = format.replace(/{
    
    (y|m|d|h|i|s|a)+}/g, (result, key) => {
    
    
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
    
     return ['日', '一', '二', '三', '四', '五', '六'][value] }
    if (result.length > 0 && value < 10) {
    
    
      value = '0' + value
    }
    return value || 0
  })
  return timeStr
}

Lugar de presentación del proyecto.

import {
    
     parseTime } from '@/utils/utils'

usar

<div>{
    
    {
    
     parseTime('传入的时间', '{
    
    y}-{
    
    m}-{
    
    d} {
    
    h}:{
    
    i}:{
    
    s}') }}</div>
<div>{
    
    {
    
     parseTime('传入的时间', '{
    
    y}-{
    
    m}-{
    
    d} {
    
    h}') }}</div>

espectáculo
Insertar descripción de la imagen aquí
Insertar descripción de la imagen aquí

Supongo que te gusta

Origin blog.csdn.net/l2345432l/article/details/127786151
Recomendado
Clasificación