用javascript设置时间格式的方法:1、使用“new Date().format('yyyy-MM-dd');”方式对时间格式化;2、通过js内置方法将日期按字符串格式输出。
本文操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。
怎么用javascript设置时间格式?
用JavaScript(js)对时间格式化
可以说是Web项目中不可或缺的一个Javascript类库,它可以帮助你快速的解决客户端编程的许多问题,下面贴出一个用js格式化时间的方法。
Date.prototype.format =function(format) { var o = { "M+" : this.getMonth()+1, //month "d+" : this.getDate(), //day "h+" : this.getHours(), //hour "m+" : this.getMinutes(), //minute "s+" : this.getSeconds(), //second "q+" : Math.floor((this.getMonth()+3)/3), //quarter "S" : this.getMilliseconds() //millisecond } if(/(y+)/.test(format)) format=format.replace(RegExp.$1, (this.getFullYear()+"").substr(4- RegExp.$1.length)); for(var k in o)if(new RegExp("("+ k +")").test(format)) format = format.replace(RegExp.$1, RegExp.$1.length==1? o[k] : ("00"+ o[k]).substr((""+ o[k]).length)); return format; }
以上代码必须先声明,然后在使用。使用方法:
var d =new Date().format('yyyy-MM-dd');
另一种方法:
在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,样例代码如下:
var df=new SimpleDateFormat();//jsJava1.0需要使用DateFormat对象,不要弄错就是了 df.applyPattern("yyyy-MM-dd HH:mm:ss"); var date=new Date(2007,3,30,10,59,51); var str=df.format(date); document.write(str);//显示结果为:2007-04-30 10:59:51
通过上面的例子你可以看出,你需要做的就是指定pattern,那么pattern中yyyy、MM等都表示什么意思呢?如果你学习过Java的日期格式化,那么你应该知道,那都是占位符,这些占位符都具有特殊的函数,例如y表示年,yyyy表示四个数字的年份,例如1982,下面列举一些pattern中支持的特殊字符及其含义(下面表格引自Java的官方文档,做了适当修改):
G Era designator [url=]Text[/url] AD y Year [url=]Year[/url] 1996; 96 M Month in year [url=]Month[/url] July; Jul; 07 w Week in year [url=]Number[/url] 27 W Week in month [url=]Number[/url] 2 D Day in year [url=]Number[/url] 189 d Day in month [url=]Number[/url] 10 F Day of week in month [url=]Number[/url] 2 E Day in week [url=]Text[/url] Tuesday; Tue a Am/pm marker [url=]Text[/url] PM H Hour in day (0-23) [url=]Number[/url] 0 k Hour in day (1-24) [url=]Number[/url] 24 K Hour in am/pm (0-11) [url=]Number[/url] 0 h Hour in am/pm (1-12) [url=]Number[/url] 12 m Minute in hour [url=]Number[/url] 30 s Second in minute [url=]Number[/url] 55 S Millisecond [url=]Number[/url] 978
推荐学习:《javascript基础教程》
The above is the detailed content of How to set time format using javascript. For more information, please follow other related articles on the PHP Chinese website!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

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.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor

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

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software