Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript formatted date

Tags:

javascript

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)

like image 813
coure2011 Avatar asked Nov 18 '25 22:11

coure2011


2 Answers

var now = new Date();
alert((now .getMonth() < 9 ? '0' : '') + (now .getMonth() + 1))
like image 110
gabel Avatar answered Nov 21 '25 11:11

gabel


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"

like image 40
user113716 Avatar answered Nov 21 '25 13:11

user113716