2017-10-15 134 views
0

我有下面的代码采取日期:Date类转换

var d = new Date(); 
var n = d.toString(); 

与输出:孙二零一七年十月十五日12时09分42秒GMT + 0300(EEST) 但我需要将其转换为下一格式: 2017-10-15 12:09:42 +0300 这可能与日期类方法,或者我应该使用一些正则表达式的输出字符串,格式化?

+0

MDN:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date – dfsq

回答

2

这可以通过一个名为moment.js的库轻松完成,请通过文档进行任何额外的调整,请查看下面的示例并让我知道这是否对您有帮助!

var moment_d = moment().format('YYYY-MM-DD hh:mm:ss ZZ'); 
 
console.log(moment_d);
<script src="https://momentjs.com/downloads/moment.min.js"></script>

+0

请不要只是添加这种依赖只是格式化一个日期,特别是在客户端。 – Jack

+0

当然会,但是对于他的需求来说,它也是完全过度的,而这是以实质性的浏览器性能为代价的。 – Jack

0

中没有任何JavaScript的Date对象将可以方便地得到你所需要的输出。另一方面,moment.js是一个80+ KB的野兽,在大多数情况下显然是过度杀伤力。

如果你寻找它们,那里有一些轻量级的解决方案。

或者,你可以解析.toISOString()的输出,它可以让你远达'2017-10-15T12:09:42.301Z',并将它与.getTimezoneOffset()结合起来,它返回从UTC(积极向西)的分钟数。

JS日期时间操作库很大,我建议你自己滚动,如果你只需要覆盖一些情况。

1

function formatDate(date) { 
 
    date = date || new Date(); // default to current time if parameter is not supplied 
 
    let formattedDate = date.toISOString(); // returns 2000-01-04T00:00:00.000Z 
 
    const timezone = date.getTimezoneOffset()/0.6; // returns timezone in minutes, so dividing by 0.6 gives us e.g -100 for -1hr 
 
    const timezoneString = String(timezone) // padStart is a method on String 
 
          .padStart(4, '0') // add zeroes to the beginning if only 1 digits 
 
          .replace(/^(-|\+)(\d{3})$/, '$10$2') // add a zero between a - or + and the first digit if needed 
 
          .replace(/^\d/, '+$&'); // add a plus to the beginning if zero timezone difference 
 

 
    formattedDate = formattedDate 
 
        .replace('T', ' ') // replace the T with a space 
 
        .replace(/\.\d{3}Z/, '') // remove the Z and milliseconds 
 
        + ' ' // add a space between timezone and time 
 
        + timezoneString; // append timezone 
 
        
 

 
    return formattedDate; 
 
} 
 

 
console.log(formatDate(new Date(2016, 08, 24, 9, 20, 0))); 
 
console.log(formatDate(new Date(2015, 03, 9, 18, 4, 30))); 
 
console.log(formatDate(new Date(1999, 12, 4))); 
 
console.log(formatDate(new Date(1999, 01, 4))); 
 
console.log('----');

相关问题