Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse ISO 8601 into date and time format using Moment js in Javascript?

I am currently using Moment js to parse an ISO 8601 string into date and time, but it is not working properly. What am I doing wrong? And I would take any other easier solutions as well.

The ISO 8601 I would like to parse: "2011-04-11T10:20:30Z" into date in string: "2011-04-11" and time in string: "10:20:30"

And tried console.log(moment("2011-04-11T10:20:30Z" ,moment.ISO_8601)) and console.log(moment("2011-04-11T10:20:30Z" , ["YYYY",moment.ISO_8601]) as a test, but it just returns an object with all different kinds of properties.

like image 641
Walter Avatar asked Sep 27 '16 23:09

Walter


People also ask

How do I read the ISO 8601 date format?

ISO 8601 represents date and time by starting with the year, followed by the month, the day, the hour, the minutes, seconds and milliseconds. For example, 2020-07-10 15:00:00.000, represents the 10th of July 2020 at 3 p.m. (in local time as there is no time zone offset specified—more on that below).

What is Moment () in JavaScript?

Moment JS allows displaying of date as per localization and in human readable format. You can use MomentJS inside a browser using the script method. It is also available with Node. js and can be installed using npm.

How do I convert ISO date to local time?

Use the getTime() method to convert an ISO date to a timestamp, e.g. new Date(isoStr). getTime() . The getTime method returns the number of milliseconds since the Unix Epoch and always uses UTC for time representation.

How do you find time from date in moment?

The moment(). hour() Method is used to get the hours from the current time or to set the hours. moment(). hours();


2 Answers

With moment.js

var str = '2011-04-11T10:20:30Z';  var date = moment(str);  var dateComponent = date.utc().format('YYYY-MM-DD');  var timeComponent = date.utc().format('HH:mm:ss');  console.log(dateComponent);  console.log(timeComponent);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>

Or simply with string manipulation

var str = '2011-04-11T10:20:30Z';  var parts = str.slice(0, -1).split('T');  var dateComponent = parts[0];  var timeComponent = parts[1];  console.log(dateComponent);  console.log(timeComponent);
like image 108
Xotic750 Avatar answered Sep 19 '22 01:09

Xotic750


There's two parts to the moment operation: reading the date/time in, and spitting it back out. You've got the first part:

moment("2011-04-11T10:20:30Z") 

but then you need to call an output function, eg:

moment("2011-04-11T10:20:30Z").format('YYYY-MM-DD h:mm:ss a') 

EDIT: However it's worth noting that Moment itself is a deprecated library, and even its authors will recommend switching to a smaller competitor: https://momentjs.com/docs/

like image 41
machineghost Avatar answered Sep 21 '22 01:09

machineghost