js date Formatting

  • 2021-07-21 07:00:08
  • OfStack

Take this as an example: yyyy-MM-dd HH: mm: ss

First of all, you have to write the template you need

options.sign = options.sign || 'yyyy-MM-dd HH:mm:ss';

Next, you can call the date function (the month 1 here must be +1, because the default starts from 0)


var d = new Date();
var year = d.getFullYear();
var month = d.getMonth()+1;
var day = d.getDate();
var hours = d.getHours();
var minutes = d.getMinutes();
var second = d.getSeconds();

Then combine the resulting date with the template, and you are done. (Here, replace is used to replace the date in the template.)


var result = options.sign;
result = result.replace('yyyy', year);
result = result.replace('MM', month);
result = result.replace('dd', day);
result = result.replace('HH', hours);
result = result.replace('mm', minutes);
result = result.replace('ss', second);
return result;

In fact, after writing, you can optimize yourself for 1 time and think about it yourself, such as: 2017-2-1 9: 2: 8- > 2017-02-01 09:02:08, etc.

In this way, I can write a function to filter 1: This uses 1 little knowledge point, such as 3-item operator, which sometimes helps a lot, so the foundation should be laid well.


var _complete = function(n){
        return (n>9) ? n : '0' + n;
}   

The function is simply encapsulated. How to use it, look at the following code, it is very simple, such as getting hours. Just filter it once.

var hours =  _complete(d.getHours());

The full code is attached below:


<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <title> Date time </title>
 </head>
 <body>
 </body>
</html>
<script type="text/javascript">
 //yyyy-MM-dd
 var getDateFormat = function(options){
  options = options || {};
  options.sign = options.sign || 'yyyy-MM-dd HH:mm:ss';
  var _complete = function(n){
   return (n>9) ? n : '0' + n;
  }
  var d = new Date();
  var year = d.getFullYear();
  var month = _complete(d.getMonth()+1);
  var day = _complete(d.getDate());
  var hours = _complete(d.getHours());
  var minutes = _complete(d.getMinutes());
  var second = _complete(d.getSeconds());
  var result = options.sign;
  result = result.replace('yyyy', year);
  result = result.replace('MM', month);
  result = result.replace('dd', day);
  result = result.replace('HH', hours);
  result = result.replace('mm', minutes);
  result = result.replace('ss', second);
  return result;
 }
 console.log(getDateFormat());
</script>


Related articles: