我以下面的格式从REST API接收日期和时间
2016-01-17T:08:44:29+0100
我想格式化这个日期和时间戳
17-01-2016 08:44:29
它应该是dd / mm / yyyy hh:mm:ss
如何在TypeScript中格式化?
您可以创建一个new Date("2016-01-17T08:44:29+0100") //removed a colon
对象,然后通过从Date
对象中提取它们来获取月,日,年,小时,分钟和秒,然后创建您的字符串。请参阅代码段:
var date = new Date("2016-01-17T08:44:29+0100"); // had to remove the colon (:) after the T in order to make it work
var day = date.getDate();
var monthIndex = date.getMonth();
var year = date.getFullYear();
var minutes = date.getMinutes();
var hours = date.getHours();
var seconds = date.getSeconds();
var myFormattedDate = day+"-"+(monthIndex+1)+"-"+year+" "+ hours+":"+minutes+":"+seconds;
document.getElementById("dateExample").innerHTML = myFormattedDate
<p id="dateExample"></p>
它不是最优雅的方式,但它有效。
你可以使用moment.js。在项目中安装时刻js
moment("2016-01-17T:08:44:29+0100").format('MM/DD/YYYY');
更多格式选项检查Moment.format()
检查这是否有用。
var reTime = /(\d+\-\d+\-\d+)\D\:(\d+\:\d+\:\d+).+/;
var originalTime = '2016-01-17T:08:44:29+0100';
var newTime = originalTime.replace(this.reTime, '$1 $2');
console.log('newTime:', newTime);
输出:
newTime: 2016-01-17 08:44:29