0

I am trying to get a date for mat like "2018-05-17T08:09:02", but when I tried below code I get "2018-05-17T8:9:2" can some one help to get "2018-05-17T08:09:02" , this format

 let d = new Date();
console.log("date>> "+d.getFullYear() + "-" + ((d.getMonth() + 1) < 10 ? '0' : '') +
 (d.getMonth() + 1) + "-" + d.getDate() + "T" +( d.getHours() )+ ":"+ d.getMinutes() + ":"+ d.getSeconds());
3
  • 1
    don't you simply want new Date().toISOString()? (it may have extra .000Z at the end that can be removed manually) Commented Jun 28, 2018 at 14:33
  • Using TS with AngularJS? Are you sure you don't wanna have this tagged as Angular (Angular 2+)? Commented Jun 28, 2018 at 14:44
  • I got it now let d = new Date(); console.log("KK"+d.getFullYear() + "-" + ((d.getMonth() + 1) < 10 ? '0' : '') + (d.getMonth() + 1) + "-" + d.getDate() + "T" +('0' + d.getHours()).slice(-2) + ":" + ('0' + d.getMinutes()).slice(-2) + ":" + ('0' + d.getSeconds()).slice(-2)); Commented Jun 28, 2018 at 14:49

1 Answer 1

1

According to How to format numbers by prepending 0 to single-digit numbers?

Your desirable answer is

let d = new Date();
console.log("date>> "+d.getFullYear() + "-" + ((d.getMonth() + 1) < 10 ? '0' : '') +
 (d.getMonth() + 1) + "-" + d.getDate() + "T" +("0" + d.getHours()).slice(-2)+ ":"+ ("0" + d.getMinutes()).slice(-2)  + ":"+ ("0" + d.getSeconds()).slice(-2));

But as @Aleksey Solovey already mentioned in the above, I also recommand to use d.toISOString().slice(0,-5).

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

Comments

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.