0

I have been searching to find a good way to convert Date object into formatted string but couldn't find quite an answer.

input value is this

1402462980000

and I output value should be in this format

dddd-dd-ddTdd:dd:dd[-,+]dd:dd
E.g., 2014-06-11T15:03:00+10:00

and the only way I can think of is doing it manually

tmpDate = new Date(1402462980000);
s1 = tmpDate.getFullYear().toString();
s2 = ('0' + tmpDate.getMonth()).slice(-2);
s3 = ('0' + tmpDate.getDate()).slice(-2);
s4 = ('0' + tmpDate.getHours()).slice(-2);
s5 = ('0' + tmpDate.getMinutes()).slice(-2);
s6 = ('0' + tmpDate.getSeconds()).slice(-2);
s7 = ('0' + (tmpDate.getHours() - tmpDate.getUTCHours())).slice(-2);
s8 = ('0' + (tmpDate.getMinutes() - tmpDate.getUTCMinutes())).slice(-2);
s1 + '-' + s2 + '-' + s3 + 'T' + s4 + ':' + s5 + ':' + s6 + '+' + s7 + ':' + s8;

and this looks a little crazy to me. I'm thinking there must be a better way. if you know please share your knowledge :) Thanks.

Eugene Yu
  • 3,708
  • 4
  • 21
  • 27
  • 1
    Looks like this has been thorougly answered here: http://stackoverflow.com/questions/2573521/how-do-i-output-an-iso-8601-formatted-string-in-javascript .. The short answer is tmpDate.toISOString() for some browsers but not all and mostly not IE. – IrishGeek82 Jun 11 '14 at 06:29
  • 3
    use moment.js. Its a very good lib for what you are asking for. – mohkhan Jun 11 '14 at 06:29
  • The `moment.js` format function (`moment.format()`) gives you excatly that. http://momentjs.com/ – source.rar Jun 11 '14 at 06:33
  • @mohkhan unfortunately I cannot use external library due to the system restriction. – Eugene Yu Jun 11 '14 at 07:04
  • @IrishGeek82 so it's more likely there isn't any better solution than manually parsing them. Thought I could achieve this by using regex or something.. – Eugene Yu Jun 11 '14 at 07:07
  • @EugeneYu Look at the answer (scoll down after clicking) to http://stackoverflow.com/questions/2573521/how-do-i-output-an-iso-8601-formatted-string-in-javascript not the question itself. The answer uses `.toISOString()` – Paul Jun 11 '14 at 07:12
  • @EugeneYu, I also expressed that you can use .toISOString() in my first comment. But it isn't supported in IE 8 and below. http://www.w3schools.com/jsref/jsref_toisostring.asp, If that doesn't matter then, you probably have solution. I just wanted you to be aware. – IrishGeek82 Jun 11 '14 at 07:22
  • @Paul wasn't the answer I was exactly looking for but it did help to clear out some of the code. Thanks for the comments :) – Eugene Yu Jun 12 '14 at 00:18
  • @IrishGeek82 Thanks for the link it did help me out :) – Eugene Yu Jun 12 '14 at 00:18

0 Answers0