zoukankan      html  css  js  c++  java
  • 日期时间转换方法

    1.获取的时间转换为想要的日期时间格式:

    function getTimetrans(){
        const date = new Date();//如果date为13位不需要乘1000
        const Y = date.getFullYear() + '-';
        const M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
        const D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
        const h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
        const m = (date.getMinutes() <10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
        const s = (date.getSeconds() <10 ? '0' + date.getSeconds() : date.getSeconds());
        return Y+M+D+h+m+s;
    }

    2.获取的时间转换为星期格式:

    function getWeekDate(){
        const date = new Date();//如果date为13位不需要乘1000
        const day = date.getDay();
        const weeks = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
        const week = weeks[day];
        return week;
    }

    3.时间转换为毫秒:

      1)方法一: getTime()/Date.parse()

    const oldTime = (new Date("2020/08/14 15:00:00")).getTime(); //得到毫秒数 
    
    //注:日期格式是:yyyy-mm-dd hh:mm:ss需要转化格式
    
    let startDate ='2020-08-14 15:00:00';
         startDate= startDate.replace(new RegExp("-","gm"),"/");
    let startDateM = (new Date(startDate)).getTime(); //得到毫秒数
    
    //或者
    let str = '2020-08-14 15:00:00';
    
    let arr = str.split(/[- : /]/);
    let startDate = Date.parse(new Date(arr[0], arr[1]-1, arr[2], arr[3], arr[4], arr[5]));
    console.log(startDate)//1597388400000

      2)方法=:valueOf()

    let dateTime = '2020-08-14 15:00:00';
    console.log(dateTime.valueOf());//2020-08-14 15:00:00

    let dateTime1 = new Date();
    console.log(dateTime1.valueOf());//1597389982770

    let dateTime2 = new Date('2020-08-14 15:00:00');
    console.log(dateTime2.valueOf());//1597388400000

    let timeVale = Date.parse('2020-08-14 15:00:00');//APP中直接使用此方法会报错
    console.log(timeVale);//1597388400000
     import moment from 'moment';//react-native项目安装的插件
    let timeVale2 = moment('2020-08-14 15:00:00').valueOf();//转换为毫秒(APP中使用不会报错)
    console.log(timeVale2);//1597388400000

     

  • 相关阅读:
    windows批处理
    网络设备巡检命令
    DOS笔记
    通过一台服务器ssh多台主机远程修改网卡ip
    DELL服务器PXE前期处理
    PXE推一半失败,HP服务器、曙光服务器删除数据
    IBM存储降级告警等一些服务器问题/dd/ethtool
    bond下改变网卡
    AndroidStudio 点9图片文件报错
    在AndroidStudio不能找到so文件问题:couldn't find libweibosdkcore.so
  • 原文地址:https://www.cnblogs.com/dreambin/p/13502445.html
Copyright © 2011-2022 走看看