Javascript格式化时间

JS里的Date对象并未提供时间格式化方法: 

var date = new Date();
console.log(date.getFullYear());//年份
console.log(date.getMonth()+1);//月份,注意getMonth()返回值为0-11,故必需加上1;
console.log(date.getDate());//一个月的第几天
console.log(date.getHours());//时
console.log(date.getMinutes());//分
console.log(date.getSeconds());//秒

要想返回格式化的时间可以封装一个方法实现:

JS的数字转字符串是:

var n = 1234;
console.log(n.toString());

 比如想得到 yyyyMMdd的格式化时间字符串:

var getYYYYMMDD(){
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth()+1;
    var day = date.getDate();
    var currentDay = '';
    if(month>9){
        currentDay += year.toString() + month.toString() + day.toString();
    }
    else{
        currentDay += year.toString() + '0' + month.toString() + day.toString();
    }
    return currentDay;
}

补充:

字符串转数字的方法:

https://blog.youkuaiyun.com/Inuyasha1121/article/details/40182105

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值