Reputation: 53
I'm getting a date from an API as
2017-04-20T07:00:00Z
How could I format it into the following?
20.04.2017
I'm using React to display the date:
<div>{props.data.day}</div>
I tried for example toISOString().slice(0, 10); but couldn't get that to work properly. I also tried looking at other answers, but couldn't find a solution yet.
Upvotes: 1
Views: 4954
Reputation: 376
You can extract the day, month and full year to then use as you wish!
var oldDate = new Date('2017-04-20T07:00:00Z');
var d = oldDate.getDay().toString();
var m = oldDate.getMonth().toString();
var y = oldDate.getFullYear().toString();
if(d.length < 2){
d = '0' + d;
}
if(m.length < 2){
m = '0' + m;
}
var myDate = d + '/' + m + '/' + y;
window.alert(myDate);
Upvotes: 0
Reputation: 121
If you store the date as string you can convert it this way:
var i ='2017-04-20T07:00:00Z';
var date = i.split('T');
console.log(date[0].split('-').reverse().join('.'))
this gives:
20.04.2017
Upvotes: 2
Reputation: 48610
You could use MomentJS to parse and format the date-string. Choose a library that already does this for you. You should worry about your business logic. Use mature; widely-used libraries to do the heavy lifting for you.
console.log(moment('2017-04-20T07:00:00Z', moment.ISO_8601).format('DD.MM.YYYY'));
.as-console-wrapper { top: 0; max-height: 100% !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
Part of software development is code-reuse. Since you are not developing a date library, you should not worry about creating one.
Upvotes: 1
Reputation: 1798
You can parse the result with Regex.
function convertDate(date){
var parsedDate = date.match(/^([\d]{4})-([\d]{2})-([\d]{2})/)
return parsedDate[2] + '.' + parsedDate[1] + '.' + parsedDate[0]
}
convertDate('2017-04-20T07:00:00Z')
Upvotes: 0
Reputation: 4161
The following should work without any third party libraries:
console.log(convertDate(new Date("2017-04-20T07:00:00Z")));
function convertDate(date) {
var day = date.getDate();
day = day < 10 ? "0" + day : day;
var month = date.getMonth() + 1;
month = month < 10 ? "0" + month : month;
var year = date.getFullYear();
return day + "." + month + "." + year;
}
This gives:
20.04.2017
You would need to add this to your component as a function and place the return value as the content of your div
.
Please note, as noted in other answers, you are better off using a third party library that can deal with timezones and other time-based problems without you having to think about it.
Upvotes: 2