0

I have a JavaScript Date object. I am submitting this to a web service. The web service expects the format to be something like this: 2014-01-01T00:00:00Z. Unfortunately, I do not even know what that format is called. It looks like its [Year]-[Month]-[Day]-T[Hours]:[Minutes]:[Seconds]Z.

I suspect that the Z means something. However, I do not know what. Is this a standard Date format? If so, is there a way I can easily convert my Date object to this format? Or, do I need to manually build it?

Thank you!

1 Answer 1

1

I do not even know what that format is called.

It's one of the forms defined by ISO-8601.

On any modern browser, you can get that form using the toISOString method, except it will include milliseconds, which your example doesn't. The endpoint you're sending to may not care; if it does, a simple replace can get rid of them:

var str = dt.toISOString().replace(/\.\d{3}/, '');

If you need to support IE8, you'll need a polyfill.

Another option is to use something like MomentJS, which offers all kinds of formatting options.

Example of toISOString and replace:

var dt = new Date();
var str = dt.toISOString().replace(/\.\d{3}/, '');
snippet.log(str);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Sign up to request clarification or add additional context in comments.

1 Comment

Wow! Phenomenal answer. Thank you for being so thorough.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.