jquery get current date time format
jquery date format
I want to get this format :
Here is what I have tried:
var today = new Date(); var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate(); var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds(); var dateTime = date+' '+time;
It's missing leading zeroes.
That's because numbers lower than 10 should be padded with zero but they aren't.
You can use
padStart function to achieve the expected result - add a leading 0 character if the length of a number is less than 2. I modified your code a little bit but all you need is to use
.toString().padStart(2, '0') on a number.
var today = new Date(); var date = [ today.getFullYear(), today.getMonth() + 1, today.getDate(), ].map((value) => value.toString().padStart(2, '0')).join('-'); var time = [ today.getHours(), today.getMinutes(), today.getSeconds(), ].map((value) => value.toString().padStart(2, '0')).join(':');; var dateTime = date + ' ' + time; console.log(dateTime);
This is pretty close to ISO 8601, so let's start with that.
const d = new Date(); d .toISOString() // Convert date to a string in the format of 2019-03-25T00:07:22.0253Z .substr(0, 19) // Strip off the milliseconds and Zulu timezone indication .replace('T', ' '); // Replace the T for "time" with a space
This leaves you with a date formatted like
You can use ternary operation for simple use. This should give you leading zero.
var today = new Date(); var date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate(); var time = today.getHours() + ":" + (today.getMinutes() < 10 ? '0' : '') + today.getMinutes() + ":" + today.getSeconds(); var dateTime = date + ' ' + time; console.log(dateTime, 'result');
You can use:
var d = new Date(); d = new Date(d.getTime() - 3000000); var date_format_str = d.getFullYear().toString()+"-"+((d.getMonth()+1).toString().length==2?(d.getMonth()+1).toString():"0"+(d.getMonth()+1).toString())+"-"+(d.getDate().toString().length==2?d.getDate().toString():"0"+d.getDate().toString())+" "+(d.getHours().toString().length==2?d.getHours().toString():"0"+d.getHours().toString())+":"+((parseInt(d.getMinutes()/5)*5).toString().length==2?(parseInt(d.getMinutes()/5)*5).toString():"0"+(parseInt(d.getMinutes()/5)*5).toString())+":00"; console.log(date_format_str);
- Why was this downvoted? It's a perfectly reasonable solution to the problem presented, and is well documented. I really don't understand Stack Overflow these days.