Home  >  Article  >  Web Front-end  >  Javascript method to format string date into yyyy-mm-dd

Javascript method to format string date into yyyy-mm-dd

高洛峰
高洛峰Original
2016-12-08 15:33:072922browse

This article mainly introduces the method of using Javascript to format a string date into yyyy-mm-dd. Not much to say below, refer to the following code

function formatDate(date) {
  var d = new Date(date),
    month = '' + (d.getMonth() + 1),
    day = '' + d.getDate(),
    year = d.getFullYear();
 
  if (month.length < 2) month = &#39;0&#39; + month;
  if (day.length < 2) day = &#39;0&#39; + day;
 
  return [year, month, day].join(&#39;-&#39;);
}

Usage:

console.log(formatDate(&#39;Sun May 13,2016&#39;));

Output:

2016-05-13
 
2014-05-11


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn