javascript - js时间戳转成四位时间XX:XX:XX
ringa_lee
ringa_lee 2017-04-10 15:30:04
[JavaScript讨论组]

js时间戳如何转成四位时间XX:XX:XX这种格式,不需要显示日期

ringa_lee
ringa_lee

ringa_lee

全部回复(4)
天蓬老师
// 对Date的扩展,将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符, 
// 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
// 例子: 
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18 
Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var 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;
}
调用: 

var time1 = new Date().Format("yyyy-MM-dd");
var time2 = new Date().Format("yyyy-MM-dd HH:mm:ss");  
巴扎黑
function formatTime (timestamp) {
    timestamp = timestamp * 1000;
    var date  = new Date(timestamp);
    var time = date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
    return time;
}
alert(formatTime(1436259202));
迷茫

是说转成YYYY-MM-DD HH:mm:ss这种格式么?
试试这样

var timestamp = Date.parse(new Date()); 
console.log(timestamp);
var date = new Date(timestamp);
console.log(date);
console.log(date.toLocaleString());
console.log(date.toLocaleDateString());
console.log(date.toLocaleTimeString());

出来的结果是:

1436258965000
Tue Jul 07 2015 16:49:25 GMT+0800 (中国标准时间)
2015/7/7 下午4:49:25
2015/7/7
下午4:49:25

再进一步转换的话有两种方式:一种是使用Date本身的一些方法自己拼,另一种是用replace替换格式化。

这里给一种用date 的方法拼的。
var formateDate = date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDay()+" "
      +date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();
console.log(formateDate);

结果是:
2015-7-2 16:58:3
PHP中文网

new Date(timestamp).toTimeString().slice(0, 8)
或者引入moment.js库也可以
moment(timestamp).format('HH:mm:ss')

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号