TypeScript Date and Time Format

I get the date and time from the REST API in the following format

2016-01-17T:08:44:29+0100 

I want to format this date and timestamp, for example

 17-01-2016 08:44:29 

It should be dd / mm / yyyy hh: mm: ss

How to format this in TypeScript?

+7
javascript datetime angular typescript
source share
3 answers

See this answer

You can create a new Date("2016-01-17T08:44:29+0100") //removed a colon object new Date("2016-01-17T08:44:29+0100") //removed a colon , and then get the month, day, year, hours, minutes and seconds by extracting them from the Date object, and then create your own string. See Snippet:

 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> 

This is not the most elegant way, but it works.

+5
source share

you can use moment.js. set js moment in your project

  moment("2016-01-17T:08:44:29+0100").format('MM/DD/YYYY'); 

to check the optional format option Moment.format ()

+4
source share

Check if this is helpful.

 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); 

Output:

 newTime: 2016-01-17 08:44:29 
0
source share

All Articles