Let say date current date is 10 Jan 2011. When I get date using js code
var now = new Date();
var currentDate = now.getDate() + '-' + (now.getMonth() + 1) + '-' + now.getFullYear();
It reutrns "10-1-2011"
but I want "10-01-2011" (2 places format)
var now = new Date();
alert((now .getMonth() < 9 ? '0' : '') + (now .getMonth() + 1))
Here's a nice short way:
('0' + (now.getMonth() + 1)).slice(-2)
So:
var currentDate = now.getDate() + '-' + ('0' + (now.getMonth() + 1)).slice(-2) + '-' + now.getFullYear();
(now.getMonth() + 1) adjust the month
'0' + prepends a "0" resulting in "01" or "012" for example
.slice(-2) slice off the last 2 characters resulting in "01" or "12"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With