Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript get date in format [duplicate]

I want to get today's date in the format of mm-dd-yyyy

I am using var currentDate = new Date(); document.write(currentDate);

I can't figure out how to format it.

I saw the examples var currentTime = new Date(YY, mm, dd); and currentTime.format("mm/dd/YY");

Both of which don't work

I finally got a properly formatted date using

var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;//January is 0!`

var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd}
if(mm<10){mm='0'+mm}
var today = mm+'/'+dd+'/'+yyyy;
document.write(today);'`

This seems very complex for such a simple task.

Is there a better way to get today's date in dd/mm/yyyy?

like image 308
Samuel Meddows Avatar asked Feb 08 '11 03:02

Samuel Meddows


4 Answers

Unfortunately there is no better way, but instead of reinventing the wheel, you could use a library to deal with parsing and formatting dates: Datejs

<plug class="shameless">

Or, if you find format specifiers ugly and hard to decipher, here's a concise formatting implementation that allows you to use human-readable format specifiers (namely, the Date instance getters themselves):

date.format("{Month:2}-{Date:2}-{FullYear}"); // mm-dd-yyyy

</plug>

like image 190
Ates Goral Avatar answered Nov 01 '22 13:11

Ates Goral


var today = new Date();

var strDate = 'Y-m-d'
  .replace('Y', today.getFullYear())
  .replace('m', today.getMonth()+1)
  .replace('d', today.getDate());
like image 36
mrded Avatar answered Nov 01 '22 12:11

mrded


Simple answer is no. Thats the only way to do it that I know of. You can probably wrap into a function that you can reuse many times.

like image 4
Victor Avatar answered Nov 01 '22 13:11

Victor


date.js is what you need. For example, snippet below is to convert a date to string as Java style

new Date().toString('M/d/yyyy')
like image 1
Bao Le Avatar answered Nov 01 '22 13:11

Bao Le