简体   繁体   中英

Convert string into real time date&time

I have JSON code:

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

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

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

However I want the output to be equal to that day and its time.

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

You can format dates like this:

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

In my experience, the most clean way to deal with Date and Time is by using moment.js . BTW, i will encourage to always store your datetime data in UTC and leave the local browser to show them in the local time zone.

To format your input you could 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> 

You can achieve without using days array

 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) })() 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM