search
HomeWeb Front-endJS TutorialHow to format time in JavaScript

How to format time in JavaScript

Mar 17, 2018 pm 01:38 PM
javascripttimeformat

本文为大家分享了javascript时间格式化的方法,分享给大家供大家参考,可以说是Web项目中不可或缺的一个Javascript类库,它可以帮助你快速的解决客户端编程的许多问题,下面贴出一个用js格式化时间的方法。

<span style="font-family: 微软雅黑, "Microsoft YaHei";">Date.prototype.format =function(format)<br/>{<br/>var o = {<br/>"M+" : this.getMonth()+1, //month<br/>"d+" : this.getDate(), //day<br/>"h+" : this.getHours(), //hour<br/>"m+" : this.getMinutes(), //minute<br/>"s+" : this.getSeconds(), //second<br/>"q+" : Math.floor((this.getMonth()+3)/3), //quarter<br/>"S" : this.getMilliseconds() //millisecond<br/>}<br/>if(/(y+)/.test(format)) format=format.replace(RegExp.$1,<br/>(this.getFullYear()+"").substr(4- RegExp.$1.length));<br/>for(var k in o)if(new RegExp("("+ k +")").test(format))<br/>format = format.replace(RegExp.$1,<br/>RegExp.$1.length==1? o[k] :<br/>("00"+ o[k]).substr((""+ o[k]).length));<br/>return format;<br/>}<br/></span>

1


<span style="font-family: 微软雅黑, " microsoft yahei>var</span> <span style="font-family: 微软雅黑, " microsoft yahei>d =</span><span style="font-family: 微软雅黑, " microsoft yahei>new</span> <span style="font-family: 微软雅黑, " microsoft yahei>Date().format(</span><span style="font-family: 微软雅黑, " microsoft yahei>'yyyy-MM-dd'</span><span style="font-family: 微软雅黑, " microsoft yahei>);</span>

以上代码必须先声明,然后在使用。使用方法:

另一种方法:

在Javascript之中,日期对象是Date,那么如何将一个日期对象按照定制的格式进行输出呢?
  可以现告诉你,Date对象有有四个内置方法,用于输出为字符串格式,分别为: 

  •   1)toGMTString,将一个日期按照GMT格式显示

  •   2)toLocaleString,将一个日期按照本地操作系统格式显示

  •   3)toLocaleDateString,按照本地格式显示一个日期对象的日期部分

  •   4)toLocaleTimeString,按照本地格式显示一个日期对象的时间部分 

  尽管Javascript的Date对象中内置提供了这些输出为字符串的方法,但是这些字符串不是我们来控制格式的,因此如果我们需要我们自己定制的特殊格式,那么又该怎么办呢?
  不用着急,JsJava中提供了专用的类,专门对日期进行指定格式的字符串输出,你可以下载JsJava-2.0.zip,引入其中的src/jsjava/text/DateFormat.js,或者直接引入jslib/jsjava-2.0.js,样例代码如下:

<span style="font-family: 微软雅黑, "Microsoft YaHei";">var df=new SimpleDateFormat();//jsJava1.0需要使用DateFormat对象,不要弄错就是了<br/>df.applyPattern("yyyy-MM-dd HH:mm:ss");<br/>var date=new Date(2015,12,18,10,59,51);<br/>var str=df.format(date);<br/>document.write(str);//显示结果为:2015-12-18 10:59:51<br/></span>
<span style="font-family: 微软雅黑, "Microsoft YaHei";">G Era designator [url=]Text[/url] AD<br/>y Year [url=]Year[/url] 1996; 96<br/>M Month in year [url=]Month[/url] July; Jul; 07<br/>w Week in year [url=]Number[/url] 27<br/>W Week in month [url=]Number[/url] 2<br/>D Day in year [url=]Number[/url] 189<br/>d Day in month [url=]Number[/url] 10<br/>F Day of week in month [url=]Number[/url] 2<br/>E Day in week [url=]Text[/url] Tuesday; Tue<br/>a Am/pm marker [url=]Text[/url] PM<br/>H Hour in day (0-23) [url=]Number[/url] 0<br/>k Hour in day (1-24) [url=]Number[/url] 24<br/>K Hour in am/pm (0-11) [url=]Number[/url] 0<br/>h Hour in am/pm (1-12) [url=]Number[/url] 12<br/>m Minute in hour [url=]Number[/url] 30<br/>s Second in minute [url=]Number[/url] 55<br/>S Millisecond [url=]Number[/url] 978<br/></span>

通过上面的例子你可以看出,你需要做的就是指定pattern,那么pattern中yyyy、MM等都表示什么意思呢?如果你学习过Java的日期格式化,那么你应该知道,那都是占位符,这些占位符都具有特殊的函数,例如y表示年,yyyy表示四个数字的年份,例如1982,下面列举一些pattern中支持的特殊字符及其含义(下面表格引自Java的官方文档,做了适当修改):

还有三种方法也分享给大家:

第一种方法:

<span style="font-family: 微软雅黑, "Microsoft YaHei";">// 对Date的扩展,将 Date 转化为指定格式的String <br/>// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符, <br/>// 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字) <br/>// 例子: <br/>// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 <br/>// (new Date()).Format("yyyy-M-d h:m:s.S")   ==> 2006-7-2 8:9:4.18 <br/>Date.prototype.Format = function(fmt) <br/>{ //author: meizz <br/> var o = { <br/>  "M+" : this.getMonth()+1,         //月份 <br/>  "d+" : this.getDate(),          //日 <br/>  "h+" : this.getHours(),          //小时 <br/>  "m+" : this.getMinutes(),         //分 <br/>  "s+" : this.getSeconds(),         //秒 <br/>  "q+" : Math.floor((this.getMonth()+3)/3), //季度 <br/>  "S" : this.getMilliseconds()       //毫秒 <br/> }; <br/> if(/(y+)/.test(fmt)) <br/>  fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); <br/> for(var k in o) <br/>  if(new RegExp("("+ k +")").test(fmt)) <br/> fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length))); <br/> return fmt; <br/>}<br/>var time1 = new Date().format("yyyy-MM-dd HH:mm:ss");   <br/>var time2 = new Date().format("yyyy-MM-dd");<br/></span>

第二种方法:

<span style="font-family: 微软雅黑, "Microsoft YaHei";"><me:script language="javascript" type="text/javascript"><!--<br/>    <br/>/**  <br/> * 对Date的扩展,将 Date 转化为指定格式的String  <br/> * 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q) 可以用 1-2 个占位符  <br/> * 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)  <br/> * eg:  <br/> * (new Date()).pattern("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423  <br/> * (new Date()).pattern("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04  <br/> * (new Date()).pattern("yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04  <br/> * (new Date()).pattern("yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 星期二 08:09:04  <br/> * (new Date()).pattern("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18  <br/> */   <br/>Date.prototype.pattern=function(fmt) {    <br/>  var o = {    <br/>  "M+" : this.getMonth()+1, //月份    <br/>  "d+" : this.getDate(), //日    <br/>  "h+" : this.getHours()%12 == 0 ? 12 : this.getHours()%12, //小时    <br/>  "H+" : this.getHours(), //小时    <br/>  "m+" : this.getMinutes(), //分    <br/>  "s+" : this.getSeconds(), //秒    <br/>  "q+" : Math.floor((this.getMonth()+3)/3), //季度    <br/>  "S" : this.getMilliseconds() //毫秒    <br/>  };    <br/>  var week = {    <br/>  "0" : "/u65e5",    <br/>  "1" : "/u4e00",    <br/>  "2" : "/u4e8c",    <br/>  "3" : "/u4e09",    <br/>  "4" : "/u56db",    <br/>  "5" : "/u4e94",    <br/>  "6" : "/u516d"   <br/>  };    <br/>  if(/(y+)/.test(fmt)){    <br/>    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));    <br/>  }    <br/>  if(/(E+)/.test(fmt)){    <br/>    fmt=fmt.replace(RegExp.$1, ((RegExp.$1.length>1) ? (RegExp.$1.length>2 ? "/u661f/u671f" : "/u5468") : "")+week[this.getDay()+""]);    <br/>  }    <br/>  for(var k in o){    <br/>    if(new RegExp("("+ k +")").test(fmt)){    <br/>      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));    <br/>    }    <br/>  }    <br/>  return fmt;    <br/>}   <br/>    <br/>var date = new Date();  <br/>window.alert(date.pattern("yyyy-MM-dd hh:mm:ss"));<br/>// --></mce:script><br/></span>

 第三种方法: 

<strong style="font-size: 14px;">Date.prototype.format = function(mask) {  <br/>    <br/>  var d = this;  <br/>    <br/>  var zeroize = function (value, length) {  <br/>    <br/>    if (!length) length = 2;  <br/>    <br/>    value = String(value);  <br/>    <br/>    for (var i = 0, zeros = &#39;&#39;; i < (length - value.length); i++) {  <br/>    <br/>      zeros += &#39;0&#39;;  <br/>    <br/>    }  <br/>    <br/>    return zeros + value;  <br/>    <br/>  };   <br/>    <br/>  return mask.replace(/"[^"]*"|&#39;[^&#39;]*&#39;|/b(?:d{1,4}|m{1,4}|yy(?:yy)?|([hHMstT])/1?|[lLZ])/b/g, function($0) {  <br/>    <br/>    switch($0) {  <br/>    <br/>      case &#39;d&#39;:  return d.getDate();  <br/>    <br/>      case &#39;dd&#39;: return zeroize(d.getDate());  <br/>    <br/>      case &#39;ddd&#39;: return [&#39;Sun&#39;,&#39;Mon&#39;,&#39;Tue&#39;,&#39;Wed&#39;,&#39;Thr&#39;,&#39;Fri&#39;,&#39;Sat&#39;][d.getDay()];  <br/>    <br/>      case &#39;dddd&#39;:  return [&#39;Sunday&#39;,&#39;Monday&#39;,&#39;Tuesday&#39;,&#39;Wednesday&#39;,&#39;Thursday&#39;,&#39;Friday&#39;,&#39;Saturday&#39;][d.getDay()];  <br/>    <br/>      case &#39;M&#39;:  return d.getMonth() + 1;  <br/>    <br/>      case &#39;MM&#39;: return zeroize(d.getMonth() + 1);  <br/>    <br/>      case &#39;MMM&#39;: return [&#39;Jan&#39;,&#39;Feb&#39;,&#39;Mar&#39;,&#39;Apr&#39;,&#39;May&#39;,&#39;Jun&#39;,&#39;Jul&#39;,&#39;Aug&#39;,&#39;Sep&#39;,&#39;Oct&#39;,&#39;Nov&#39;,&#39;Dec&#39;][d.getMonth()];  <br/>    <br/>      case &#39;MMMM&#39;:  return [&#39;January&#39;,&#39;February&#39;,&#39;March&#39;,&#39;April&#39;,&#39;May&#39;,&#39;June&#39;,&#39;July&#39;,&#39;August&#39;,&#39;September&#39;,&#39;October&#39;,&#39;November&#39;,&#39;December&#39;][d.getMonth()];  <br/>    <br/>      case &#39;yy&#39;: return String(d.getFullYear()).substr(2);  <br/>    <br/>      case &#39;yyyy&#39;:  return d.getFullYear();  <br/>    <br/>      case &#39;h&#39;:  return d.getHours() % 12 || 12;  <br/>    <br/>      case &#39;hh&#39;: return zeroize(d.getHours() % 12 || 12);  <br/>    <br/>      case &#39;H&#39;:  return d.getHours();  <br/>    <br/>      case &#39;HH&#39;: return zeroize(d.getHours());  <br/>    <br/>      case &#39;m&#39;:  return d.getMinutes();  <br/>    <br/>      case &#39;mm&#39;: return zeroize(d.getMinutes());  <br/>    <br/>      case &#39;s&#39;:  return d.getSeconds();  <br/>    <br/>      case &#39;ss&#39;: return zeroize(d.getSeconds());  <br/>    <br/>      case &#39;l&#39;:  return zeroize(d.getMilliseconds(), 3);  <br/>    <br/>      case &#39;L&#39;:  var m = d.getMilliseconds();  <br/>    <br/>          if (m > 99) m = Math.round(m / 10);  <br/>    <br/>          return zeroize(m);  <br/>    <br/>      case &#39;tt&#39;: return d.getHours() < 12 ? &#39;am&#39; : &#39;pm&#39;;  <br/>    <br/>      case &#39;TT&#39;: return d.getHours() < 12 ? &#39;AM&#39; : &#39;PM&#39;;  <br/>    <br/>      case &#39;Z&#39;:  return d.toUTCString().match(/[A-Z]+$/);  <br/>    <br/>      // Return quoted strings with the surrounding quotes removed  <br/>    <br/>      default:  return $0.substr(1, $0.length - 2);  <br/>    <br/>    }  <br/>    <br/>  });  <br/>    <br/>};<br/></strong>

The above is the detailed content of How to format time in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

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
Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)