Convert string to date and time in real time

I have a JSON code:

{ "time":"2015-10-20T11:20:00+02:00" } 

I read that JSON from my script and the output in the table:

 2015-10-20T11:20:00+02:00 

However, I want the result to be equal to this day and time.

For example: Tue 20:00 (if my time zone is +02)

+7
json javascript
source share
3 answers

You can format dates as follows:

 var date = new Date('2015-10-20T11:20:00+02:00'); var days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']; var output = days[date.getDay()] + ' ' + date.getHours() + ':' + date.getMinutes(); console.log(output); // Tue 6:20 
+7
source share

In my experience, the cleanest way to deal with date and time is to use moment.js . BTW, I will recommend always storing your datetime data in UTC and leaving the local browser to display in the local time zone.

To format your input, you can do the following:

 var vrijeme = "2015-10-20T11:20:00+02:00", date = moment(vrijeme, moment.ISO_8601); var formatted = date.format('ddd h:mm'); console.log(formatted); // open the console with F12 to see the results 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script> 
+3
source share

You can achieve without using an array of days

 function getTwoDigitValue(str) { return str.toString().length == 1 ? "0" + str : str; } (function() { var date = new Date('2015-10-20T11:20:00+02:00'); var output = date.toString().split(" ")[0] + " " + getTwoDigitValue(date.getHours()) + ":" + getTwoDigitValue(date.getMinutes()); console.log(output) })() 
+1
source share

All Articles