js获取当地时间并且拼接时间格式的三种方式

本文介绍了几种使用JavaScript获取并格式化当前时间的方法,包括利用Date对象的原生方法及自定义函数实现时间格式化,适用于不同场景的需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    js获取当地时间并且拼接时间格式,在stackoverflow上有人在问,查了资料,各种方法将时间格式改成任意自己想要的样式。

    1.

[javascript] view plain copy
print ?
  1. var date = new Date(+new Date()+8*3600*1000).toISOString().replace(/T/g,' ').replace(/\.[\d]{3}Z/,'');  
  2. console.log(date);//2017-01-22 11:08:46  
   var date = new Date(+new Date()+8*3600*1000).toISOString().replace(/T/g,' ').replace(/\.[\d]{3}Z/,'');
   console.log(date);//2017-01-22 11:08:46
    2.        
[javascript] view plain copy
print ?
  1. var date = new Date();  
  2. var strDate = date.toLocaleString().replace(/[年月]/g,'-').replace(/[日上下午]/g,'');  
  3. console.log(strDate);//  2017/1/22 11:11:56  
   var date = new Date();
   var strDate = date.toLocaleString().replace(/[年月]/g,'-').replace(/[日上下午]/g,'');
   console.log(strDate);//  2017/1/22 11:11:56
   3.字符串拼接方式
[javascript] view plain copy
print ?
  1.   function getNowFormatDate() {  
  2.             var date = new Date();  
  3.     var seperator1 = "-";  
  4.     var seperator2 = ":";  
  5.     var month = date.getMonth() + 1;  
  6.      
  7.     var strDate = date.getDate();  
  8.     if (month >= 1 && month <= 9) {  
  9.         month = "0" + month;  
  10.     }  
  11.     if (strDate >= 0 && strDate <= 9) {  
  12.         strDate = "0" + strDate;  
  13.     }  
  14.       
  15.     var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate  
  16.             + " " + date.getHours() + seperator2 + date.getMinutes()  
  17.             + seperator2 + date.getSeconds();  
  18.     return currentdate;  
  19. }   
  20. var data = getNowFormatDate();  
  21. console.log(data);  //2017-01-22 11:14:16  
         function getNowFormatDate() {
                var date = new Date();
                var seperator1 = "-";
                var seperator2 = ":";
                var month = date.getMonth() + 1;
               
                var strDate = date.getDate();
                if (month >= 1 && month <= 9) {
                    month = "0" + month;
                }
                if (strDate >= 0 && strDate <= 9) {
                    strDate = "0" + strDate;
                }
                
                var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
                        + " " + date.getHours() + seperator2 + date.getMinutes()
                        + seperator2 + date.getSeconds();
                return currentdate;
            } 
            var data = getNowFormatDate();
            console.log(data);  //2017-01-22 11:14:16


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值