Home>

This article summarizes several common methods for formatting date and time in JavaScript.I am more interested in the last personalized output time.Basically as long as it can be used in the project,Recommended for friends.

method one:

//extension of date, convert date to string of specified format
//month (m), day (d), hour (h), minute (m), second (s), quarter (q) can use 1-2 placeholders,//year (y) can use 1-4 placeholders,Milliseconds (s) can only use 1 placeholder (a 1-3 digit number)
//Example:
//(new date ()). format ("yyyy-mm-dd hh:mm:ss.s") ==>2006-07-02 08:09:04.423
//(new date ()). format ("yyyy-m-d h:m:s.s") ==>2006-7-2 8:9:4.18
date.prototype.format=function (fmt) {//author:meizz
  var o={
    "m +":this.getmonth () + 1, //month
    "d +":this.getdate (), //day
    "h +":this.gethours (), //hours
    "m +":this.getminutes (), //minutes
    "s +":this.getseconds (), //second
    "q +":math.floor ((this.getmonth () + 3)/3), //quarter
    "s":this.getmilliseconds () //ms
  };
  if (/(y+)/.test(fmt)) fmt=fmt.replace (regexp. $1, (this.getfullyear () + "") .substr (4-regexp. $1.length));
  for (var k in o)
  if (new regexp ("(" + k + ")"). test (fmt)) fmt=fmt.replace (regexp. $1, (regexp. $1.length == 1)?(o [k] ):(("00" + o [k]). Substr (("" + o [k]). Length)));
  return fmt;
}

Calling method:

var time1=new date (). format ("yyyy-mm-dd");

var time2=new date (). format ("yyyy-mm-dd hh:mm:ss");

Method Two:

<script language="javascript" type="text/javascript">
<!-/** * An extension to date to convert date to a string of the specified format * month (m), day (d), 12 hours (h), 24 hours (h), minutes (m), Second (s), week (e), quarter (q)
  1-2 placeholders can be used * year (y) can be 1-4 placeholders,Milliseconds (s) can only use 1 placeholder (a 1-3 digit number) * eg:* (new
  date ()). pattern ("yyyy-mm-dd hh:mm:ss.s") ==>2006-07-02 08:09:04.423
 * (new date ()). pattern ("yyyy-mm-dd e hh:mm:ss") ==>2009-03-10 Tuesday 20:09:04
 * (new date ()). pattern ("yyyy-mm-dd ee hh:mm:ss") ==>Tuesday, March 10, 2009 08:09:04
 * (new date ()). pattern ("yyyy-mm-dd eee hh:mm:ss") ==>Tuesday, March 10, 2009 08:09:04
 * (new date ()). pattern ("yyyy-m-d h:m:s.s") ==>2006-7-2 8:9:4.18
 * /
date.prototype.pattern=function (fmt) {
  var o={
  "m +":this.getmonth () + 1, //month
  "d +":this.getdate (), //day
  "h +":this.gethours ()%12 == 0?12:this.gethours ()%12, //hour
  "h +":this.gethours (), //hours
  "m +":this.getminutes (), //minutes
  "s +":this.getseconds (), //seconds
  "q +":math.floor ((this.getmonth () + 3)/3), //quarter
  "s":this.getmilliseconds () //ms
  };
  var week={
  "0":"/u65e5",  "1":"/u4e00",  "2":"/u4e8c",  "3":"/u4e09",  "4":"/u56db",  "5":"/u4e94",  "6":"/u516d"
  };
  if (/(y +) /. test (fmt)) {
    fmt=fmt.replace (regexp. $1, (this.getfullyear () + ""). substr (4-regexp. $1.length));
  }
  if (/(e +) /. test (fmt)) {
    fmt=fmt.replace (regexp. $1, ((regexp. $1.length>1)?(regexp. $1.length>2?"/u661f/u671f":"/u5468"):" ") + week [this.getday () +" "]);
  }
  for (var k in o) {
    if (new regexp ("(" + k + ")"). test (fmt)) {
      fmt=fmt.replace (regexp. $1, (regexp. $1.length == 1)?(o [k]):(("00" + o [k]). substr (("" + o [k]). length)));
    }
  }
  return fmt;
}
var date=new date ();
window.alert (date.pattern ("yyyy-mm-dd hh:mm:ss"));
//->
</script>

Method three:

date.prototype.format=function (mask) {
  var d=this;
  var zeroize=function (value, length) {
      if (! length) length=2;
      value=string (value);
      for (var i=0, zeros="";i<(length-value.length);i ++) {
        zeros +="0";
      }
      return zeros + value;
    };
  return mask.replace (/"[^"] * "|" [^ "] *" |/b (?:d {
    1, 4
  } | m {
    1, 4
  } | yy (?:yy)?| ([hhmstt])/1?| [llz])/b/g, function ($0) {
    switch ($0) {
    case "d":
      return d.getdate ();
    case "dd":
      return zeroize (d.getdate ());
    case "ddd":
      return ["sun", "mon", "tue", "wed", "thr", "fri", "sat"] [d.getday ()];
    case "dddd":
      return ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"] [d.getday ()];
    case "m":
      return d.getmonth () + 1;
    case "mm":
      return zeroize (d.getmonth () + 1);
    case "mmm":
      return ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"] [d.getmonth ()];
    case "mmmm":
      return ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"] [d.getmonth ()];
    case "yy":
      return string (d.getfullyear ()). substr (2);
    case "yyyy":
      return d.getfullyear ();
    case "h":
      return d.gethours ()%12 || 12;
    case "hh":
      return zeroize (d.gethours ()%12 || 12);
    case "h":
      return d.gethours ();
    case "hh":
      return zeroize (d.gethours ());
    case "m":
      return d.getminutes ();
    case "mm":
      return zeroize (d.getminutes ());
    case "s":
      return d.getseconds ();
    case "ss":
      return zeroize (d.getseconds ());
    case "l":
      return zeroize (d.getmilliseconds (), 3);
    case "l":
      var m=d.getmilliseconds ();
      if (m>99) m=math.round (m/10);
      return zeroize (m);
    case "tt":
      return d.gethours ()<12?"am":"pm";
    case "tt":
      return d.gethours ()<12?"am":"pm";
    case "z":
      return d.toutcstring (). match (/[a-z] + $/);
      //return quoted strings with the surrounding quotes removed
    default:
      return $0.substr (1, $0.length-2);
    }
  });
};

Method four:

<script type="text/javascript">
var date=new date ();
document.writeln (date);
//thu jan 08 2015 01:25:53 gmt + 0800 (China Standard Time)
document.writeln (date.parse ());
//nan
document.writeln (date.parse ("6/10/2014"));
//1402329600000 milliseconds
document.writeln (date.parse ("thu jan 08 2015 01:25:53"));
//1420651553000 milliseconds
document.writeln (date.utc ());
//nan
//Date formatting method
document.writeln ("<br />");
document.writeln (date.todatestring ());
//thu jan 08 2015
document.writeln ("<br />")
document.writeln (date.totimestring ());
//01:39:08 gmt + 0800 (China Standard Time)
document.writeln ("<br />")
document.writeln (date.tolocaledatestring ());
//January 8, 2015
document.writeln ("<br />")
document.writeln (date.tolocaletimestring ());
//1:39:08 am
document.writeln ("<br />")
document.writeln (date.toutcstring ());
//wed, 07 jan 2015 17:39:08 gmt
//some set, get methods
</script>

Method five:

date.prototype.format=function (formatstr) {
var str=formatstr;
var week=["Sun", "One", "Two", "Three", "Four", "Five", "Six"];
str=str.replace (/yyyy | yyyy /, this.getfullyear ());
str=str.replace (/yy | yy /, (this.getyear ()%100)>9?(this.getyear ()%100) .tostring ():"0" + (this.getyear ()%100));
str=str.replace (/mm /, (this.getmonth () + 1)>9?(this.getmonth () + 1) .tostring ():"0" + (this.getmonth () + 1));
str=str.replace (/m/g, (this.getmonth () + 1));
str=str.replace (/w | w/g, week [this.getday ()]);
str=str.replace (/dd | dd /, this.getdate ()>9?this.getdate (). tostring ():"0" + this.getdate ());
str=str.replace (/d | d/g, this.getdate ());
str=str.replace (/hh | hh /, this.gethours ()>9?this.gethours (). tostring ():"0" + this.gethours ());
str=str.replace (/h | h/g, this.gethours ());
str=str.replace (/mm /, this.getminutes ()>9?this.getminutes (). tostring ():"0" + this.getminutes ());
str=str.replace (/m/g, this.getminutes ());
str=str.replace (/ss | ss /, this.getseconds ()>9?this.getseconds (). tostring ():"0" + this.getseconds ());
str=str.replace (/s | s/g, this.getseconds ());
return str
}

Method six:

date.prototype.format=function (formatstr) {
var str=formatstr;
var week=["Sun", "One", "Two", "Three", "Four", "Five", "Six"];
str=str.replace (/yyyy | yyyy /, this.getfullyear ());
str=str.replace (/yy | yy /, (this.getyear ()%100)>9?(this.getyear ()%100) .tostring ():"0" + (this.getyear ()%100));
str=str.replace (/mm /, (this.getmonth () + 1)>9?(this.getmonth () + 1) .tostring ():"0" + (this.getmonth () + 1));
str=str.replace (/m/g, (this.getmonth () + 1));
str=str.replace (/w | w/g, week [this.getday ()]);
str=str.replace (/dd | dd /, this.getdate ()>9?this.getdate (). tostring ():"0" + this.getdate ());
str=str.replace (/d | d/g, this.getdate ());
str=str.replace (/hh | hh /, this.gethours ()>9?this.gethours (). tostring ():"0" + this.gethours ());
str=str.replace (/h | h/g, this.gethours ());
str=str.replace (/mm /, this.getminutes ()>9?this.getminutes (). tostring ():"0" + this.getminutes ());
str=str.replace (/m/g, this.getminutes ());
str=str.replace (/ss | ss /, this.getseconds ()>9?this.getseconds (). tostring ():"0" + this.getseconds ());
str=str.replace (/s | s/g, this.getseconds ());
return str
}

Method seven:

/*
1.<60s, displayed as "just now"
2.>= 1min&&<60 min, showing the difference from the current time "xx minutes ago"
3.>= 60min&&<1day, display the difference from the current time "today xx:xx"
4.>= 1day&&<1year, display the date "xx month xx day xx:xx"
5.>= 1year, display specific date "xxxx year xx month xx day xx:xx"
* /
function timeformat (time) {
var date=new date (time),curdate=new date (),year=date.getfullyear (),month=date.getmonth () + 10,day=date.getdate (),hour=date.gethours (),minute=date.getminutes (),curyear=curdate.getfullyear (),curhour=curdate.gethours (),timestr;
if (year<curyear) {
timestr=year + "year" + month + "month" + day + "day" + hour + ":" + minute;
} else {
var pasttime=curdate-date,pasth=pasttime/3600000;
if (pasth>curhour) {
timestr=month + "month" + day + "day" + hour + ":" + minute;
} else if (pasth>= 1) {
timestr="Today" + hour + ":" + minute + "minute";
} else {
var pastm=curdate.getminutes ()-minute;
if (pastm>1) {
timestr=pastm + "minutes ago";
} else {
timestr="just now";
}
}
}
return timestr;
}

Isn't the seventh one more personalized?Personally recommend this

  • Previous Analyze warnings and processing when iOS runs out of memory
  • Next Case Study Try {} Catch {} Function