本文为大家分享了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 |
|
以上代码必须先声明,然后在使用。使用方法:
另一种方法:
在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 = ''; i < (length - value.length); i++) { <br/> <br/> zeros += '0'; <br/> <br/> } <br/> <br/> return zeros + value; <br/> <br/> }; <br/> <br/> return mask.replace(/"[^"]*"|'[^']*'|/b(?:d{1,4}|m{1,4}|yy(?:yy)?|([hHMstT])/1?|[lLZ])/b/g, function($0) { <br/> <br/> switch($0) { <br/> <br/> case 'd': return d.getDate(); <br/> <br/> case 'dd': return zeroize(d.getDate()); <br/> <br/> case 'ddd': return ['Sun','Mon','Tue','Wed','Thr','Fri','Sat'][d.getDay()]; <br/> <br/> case 'dddd': return ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'][d.getDay()]; <br/> <br/> case 'M': return d.getMonth() + 1; <br/> <br/> case 'MM': return zeroize(d.getMonth() + 1); <br/> <br/> case 'MMM': return ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'][d.getMonth()]; <br/> <br/> case 'MMMM': return ['January','February','March','April','May','June','July','August','September','October','November','December'][d.getMonth()]; <br/> <br/> case 'yy': return String(d.getFullYear()).substr(2); <br/> <br/> case 'yyyy': return d.getFullYear(); <br/> <br/> case 'h': return d.getHours() % 12 || 12; <br/> <br/> case 'hh': return zeroize(d.getHours() % 12 || 12); <br/> <br/> case 'H': return d.getHours(); <br/> <br/> case 'HH': return zeroize(d.getHours()); <br/> <br/> case 'm': return d.getMinutes(); <br/> <br/> case 'mm': return zeroize(d.getMinutes()); <br/> <br/> case 's': return d.getSeconds(); <br/> <br/> case 'ss': return zeroize(d.getSeconds()); <br/> <br/> case 'l': return zeroize(d.getMilliseconds(), 3); <br/> <br/> case 'L': var m = d.getMilliseconds(); <br/> <br/> if (m > 99) m = Math.round(m / 10); <br/> <br/> return zeroize(m); <br/> <br/> case 'tt': return d.getHours() < 12 ? 'am' : 'pm'; <br/> <br/> case 'TT': return d.getHours() < 12 ? 'AM' : 'PM'; <br/> <br/> case 'Z': 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!

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 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.

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.

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.

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.

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

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 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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Atom editor mac version download
The most popular open source editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version
God-level code editing software (SublimeText3)