关于使用JS获取当前时间并格式化输出

一、Data对象的常用方法


const myDate = new Date();
myDate.getYear(); //获取当前年份(2位)
myDate.getFullYear(); //获取完整的年份(4位,1970-????)
myDate.getMonth(); //获取当前月份(0-11,0代表1月)
myDate.getDate(); //获取当前日(1-31)
myDate.getDay(); //获取当前星期X(0-6,0代表星期天)
myDate.getTime(); //获取当前时间(从1970.1.1开始的毫秒数)
myDate.getHours(); //获取当前小时数(0-23)
myDate.getMinutes(); //获取当前分钟数(0-59)
myDate.getSeconds(); //获取当前秒数(0-59)
myDate.getMilliseconds(); //获取当前毫秒数(0-999)
myDate.toLocaleDateString(); //获取当前日期
myDate.toLocaleTimeString(); //获取当前时间

myDate.toLocaleString( ); //获取日期与时间
//toLocaleString( )方法默认输出格式为 '2023/4/1 22:22:18'

在这里插入图片描述

二、格式化输出

(1)逐个提取并拼接字符串

function printDate() {
    
    
  const d = new Date();
  const year = d.getFullYear();
  const month = d.getMonth() > 8 ? d.getMonth() + 1 : "0" + (d.getMonth() + 1);
  const date = d.getDate() > 9 ? d.getDate() : "0" + d.getDate();
  const hours = d.getHours() > 9 ? d.getHours() : "0" + d.getHours();
  const minutes = d.getMinutes() > 9 ? d.getMinutes() : "0" + d.getMinutes();
  const seconds = d.getSeconds() > 9 ? d.getSeconds() : "0" + d.getSeconds();
  return `${
      
      year}-${
      
      month}-${
      
      date} ${
      
      hours}:${
      
      minutes}:${
      
      seconds}`;
}

在这里插入图片描述
在这里插入图片描述

(2)一步到位提取年月日时分秒(重点)

首先,提取数据到数据

function extract(){
    
    
  const d = new Date(new Date().getTime() + 8*3600*1000);
  return new Date(d).toISOString().split(/[^0-9]/).slice(0,-2);
}

在这里插入图片描述
然后,拼接数据格式化输出

function forTime(){
    
    
    const d = new Date(new Date().getTime() + 8*3600*1000);
    const dList = d.toISOString().split(/[^0-9]/).slice(0,-2);
    return `${
      
      dList[0]}${
      
      dList[1]}${
      
      dList[2]}${
      
      dList[3]}${
      
      dList[4]}${
      
      dList[5]}`
}

在这里插入图片描述
(附上,过程剖析)
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43426379/article/details/129904282
今日推荐