Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a date in YYYY-MM-DD format?

Normally if I wanted to get the date I could just do something like

var d = new Date(); console.log(d);

The problem with doing that, is when I run that code, it returns:

Mon Aug 24 2015 4:20:00 GMT-0800 (Pacific Standard Time)

How could I get the Date() method to return a value in a "MM-DD-YYYY" format so it would return something like:

8/24/2015

Or, maybe MM-DD-YYYY H:M

8/24/2016 4:20

like image 572
OneStig Avatar asked Aug 24 '15 22:08

OneStig


People also ask

How do I get the current date in YYYY-MM-DD format?

To get today's date in (YYYY-MM-DD) format in MySQL, you can use CURDATE().

What is YYYY-MM-DD format example?

yyyy-MM-dd — Example: 2013-06-23.

Is there a date format YYYY DD MM?

The ISO 8601 format YYYY-MM-DD (2022-08-30) is intended to harmonize these formats and ensure accuracy in all situations. Many countries have adopted it as their sole official date format, though even in these areas writers may adopt abbreviated formats that are no longer recommended.


3 Answers

Just use the built-in .toISOString() method like so: toISOString().split('T')[0]. Simple, clean and all in a single line.

var date = (new Date()).toISOString().split('T')[0];
document.getElementById('date').innerHTML = date;
<div id="date"></div>

Please note that the timezone of the formatted string is UTC rather than local time.

like image 169
leaksterrr Avatar answered Oct 25 '22 18:10

leaksterrr


The below code is a way of doing it. If you have a date, pass it to the convertDate() function and it will return a string in the YYYY-MM-DD format:

var todaysDate = new Date();

function convertDate(date) {
  var yyyy = date.getFullYear().toString();
  var mm = (date.getMonth()+1).toString();
  var dd  = date.getDate().toString();

  var mmChars = mm.split('');
  var ddChars = dd.split('');

  return yyyy + '-' + (mmChars[1]?mm:"0"+mmChars[0]) + '-' + (ddChars[1]?dd:"0"+ddChars[0]);
}

console.log(convertDate(todaysDate)); // Returns: 2015-08-25
like image 39
Starfish Avatar answered Oct 25 '22 18:10

Starfish


Yet another way:

var today = new Date().getFullYear()+'-'+("0"+(new Date().getMonth()+1)).slice(-2)+'-'+("0"+new Date().getDate()).slice(-2)
document.getElementById("today").innerHTML = today
<div id="today">
like image 36
DevonDahon Avatar answered Oct 25 '22 20:10

DevonDahon