关于在前端js中将时间戳转换为2000-01-01 00:00:00的格式

一、首先获取时间戳(原文链接)

1.Date.now();

console.log(Date.now()) //1642471441587

2.Date.parse();

Date.parse(new Date()) //1642471535000
Date.parse("2022/1/18 10:05") //1642471500000
不推荐这种办法,毫秒级别的数值被转化为000。

3.valueOf()

(new Date()).valueOf() //1642471624512
通过valueOf()函数返回指定对象的原始值获得准确的时间戳值

4.getTime()

new Date().getTime() //1642471711588
通过原型方法直接获得当前时间的毫秒值,准确

5.Number

Number(new Date()) //1642471746435
将时间对象转化为一个number类型的数值,即时间戳

二、js把时间戳转换为时间格式原文链接

// 用法:
// 需要显示秒:getMyDate(1523927510, true)
// 不需要显示秒:① getMyDate(1523927510, false) ② getMyDate(1523927510)
// 如果只需要时间: getMyDate(1523927510, true).split(" ")[1];
// 如果只需要日期: getMyDate(1523927510, true).split(" ")[0]; 

// 参数 str 为时间戳 可以传入10位也可以传入13位
// 参数 bool的值可传true或者false或者不传,如果需要显示秒则传true,不需要显示则传false或者不传

function getMyDate(str, bool){ 
    if(str > 9999999999) { // 这里判断:时间戳为几位数
        var c_Date = new Date(parseInt(str));
    } else {
        var c_Date = new Date(parseInt(str) * 1000);
    }
    var c_Year = c_Date.getFullYear(), 
    c_Month = c_Date.getMonth()+1, 
    c_Day = c_Date.getDate(),
    c_Hour = c_Date.getHours(), 
    c_Min = c_Date.getMinutes(), 
    c_Sen = c_Date.getSeconds();
    if(bool) { // 判断是否需要显示秒
        var c_Time = c_Year +'-'+ getzf(c_Month) +'-'+ getzf(c_Day) +' '+ getzf(c_Hour) +':'+ getzf(c_Min) +':'+getzf(c_Sen);//最后拼接时间 
    } else {
        var c_Time = c_Year +'-'+ getzf(c_Month) +'-'+ getzf(c_Day) +' '+ getzf(c_Hour) +':'+ getzf(c_Min);//最后拼接时间 
    }
    return c_Time;
};
//补0操作  小于10的就在数字前面加0,这应该很好理解吧

function getzf(c_num){ 
    if(parseInt(c_num) < 10){ 
        c_num = '0' + c_num; 
    } 
    return c_num; 
}

三、获取时间的其他方法

 1 myDate.getYear(); //获取当前年份(2位)
 2 myDate.getFullYear(); //获取完整的年份(4位,1970-????)
 3 myDate.getMonth(); //获取当前月份(0-11,0代表1月)
 4 myDate.getDate(); //获取当前日(1-31)
 5 myDate.getDay(); //获取当前星期X(0-6,0代表星期天)
 6 myDate.getTime(); //获取当前时间(从1970.1.1开始的毫秒数)
 7 myDate.getHours(); //获取当前小时数(0-23)
 8 myDate.getMinutes(); //获取当前分钟数(0-59)
 9 myDate.getSeconds(); //获取当前秒数(0-59)
10 myDate.getMilliseconds(); //获取当前毫秒数(0-999)
11 myDate.toLocaleDateString(); //获取当前日期(年月日)
12 var mytime=myDate.toLocaleTimeString(); //获取当前时间(时分秒)
13 myDate.toLocaleString( ); //获取日期与时间(年月日时分秒)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值