Christopher Marshall
Christopher Marshall

Reputation: 10736

How to convert time and date string to ISO format

I have two inputs, a time and a date input. I'm trying to format them as an ISO string to send to the backend using moment.js.

This is what I have so far 01:00 2016-01-01, I need to format or convert that to ISO. Is there a way to do it using Moment?

Upvotes: 3

Views: 3931

Answers (3)

Alex Nolasco
Alex Nolasco

Reputation: 19456

Assuming you are referring to ISO8601 and momentjs (2.10.6), I currently do it like this

var example = momentObject.format("YYYY-MM-DD[T]HH:mm:ss");

Upvotes: 2

Maugdog
Maugdog

Reputation: 51

You need to use moment's parse function to first create the correct moment object from the data that you have (assuming a 24-hour clock, and month listed before the days):

var myMoment = moment("01:00 2016-01-01", "HH:mm YYYY-MM-DD");

Then you can use moment's format function to output the date in the ISO format that you want. Note that calling the format function without any parameters will output ISO 8601 by default:

myMoment.format();

See the moment docs for more info here.

Hope this helps!

Upvotes: 2

g.pickardou
g.pickardou

Reputation: 35832

To convert ISO I recommend the more standard

date.format();

or

JSON.stringify(yourDate)

or if you prefer momentjs:

var date = moment();
date.toISOString();

or

moment(yourDate).format('MM/DD/YYYY'); // <- your custom format string

To know what are the momentjs formatting rules start reading here

Upvotes: 3

Related Questions