Home Web Front-end JS Tutorial js formatting time summary

js formatting time summary

May 16, 2016 pm 04:32 PM
js time format

在项目中,我们经常要遇到对日期时间进行格式化,下面我们就来先小结一下各种时间格式化的方法,然后再通过实例来进行分析。

废话不多说,先把各种格式化方法贴给大家

var myDate = new Date();

myDate.getYear(); //获取当前年份(2位)
myDate.getFullYear(); //获取完整的年份(4位,1970-????)
myDate.getMonth(); //获取当前月份(0-11,0代表1月)
myDate.getDate(); //获取当前日(1-31)
myDate.getDay(); //获取当前星期X(0-6,0代表星期天)
myDate.getTime(); //获取当前时间(从1970.1.1开始的毫秒数)
myDate.getHours(); //获取当前小时数(0-23)
myDate.getMinutes(); //获取当前分钟数(0-59)
myDate.getSeconds(); //获取当前秒数(0-59)
myDate.getMilliseconds(); //获取当前毫秒数(0-999)
myDate.toLocaleDateString(); //获取当前日期
var mytime=myDate.toLocaleTimeString(); //获取当前时间
myDate.toLocaleString( ); //获取日期与时间
Copy after login

可以说是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;
}
Copy after login

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

var d =new Date().format('yyyy-MM-dd');
Copy after login

另一种方法:

在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
Copy after login

通过上面的例子你可以看出,你需要做的就是指定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
Copy after login

以上就是本章的全部内容,更多相关教程请访问JavaScript视频教程

Statement of this Website
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

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)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to format c drive with dos command How to format c drive with dos command Feb 19, 2024 pm 04:23 PM

DOS command is a command line tool used in Windows operating system, which can be used to perform various system management tasks and operations. One of the common tasks is to format the hard drive, including the C drive. Formatting the C drive is a relatively dangerous operation because it will erase all data on the C drive and reinitialize the file system. Before performing this operation, make sure you have backed up important files and have a clear understanding of the impact that formatting will have on your computer. The following is formatted in the DOS command line

How much does a Douyin level 10 light sign cost? How many days does it take to create a level 10 fan sign? How much does a Douyin level 10 light sign cost? How many days does it take to create a level 10 fan sign? Mar 11, 2024 pm 05:37 PM

On the Douyin platform, many users are eager to obtain level certification, and the level 10 light sign shows the user's influence and recognition on Douyin. This article will delve into the price of Douyin’s level 10 light boards and the time it takes to reach this level to help users better understand the process. 1. How much does a level 10 Douyin light sign cost? The price of Douyin's 10-level light signs will vary depending on market fluctuations and supply and demand. The general price ranges from a few thousand yuan to ten thousand yuan. This price mainly includes the cost of the light sign itself and possible service fees. Users can purchase level 10 light signs through Douyin’s official channels or third-party service agencies, but they should pay attention to legal channels when purchasing to avoid false or fraudulent transactions. 2. How many days does it take to create a level 10 fan sign? Reach level 10 light sign

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How long does it take to clear the Elden Ring? How long does it take to clear the Elden Ring? Mar 11, 2024 pm 12:50 PM

Players can experience the main plot of the game and collect game achievements when playing in Elden's Circle. Many players don't know how long it takes to clear Elden's Circle. The player's clearance process is 30 hours. How long does it take to clear the Elden Ring? Answer: 30 hours. 1. Although this 30-hour clearance time does not refer to a master-like speed pass, it also omits a lot of processes. 2. If you want to get a better game experience or experience the complete plot, then you will definitely need to spend more time on the duration. 3. If players collect them all, it will take about 100-120 hours. 4. If you only take the main line to brush BOSS, it will take about 50-60 hours. 5. If you want to experience it all: 150 hours of base time.

How to set the time for publishing works on Xiaohongshu? Is the time for publishing the work accurate? How to set the time for publishing works on Xiaohongshu? Is the time for publishing the work accurate? Mar 24, 2024 pm 01:31 PM

Xiaohongshu, a platform full of life and knowledge sharing, allows more and more creators to express their opinions freely. In order to get more attention and likes on Xiaohongshu, in addition to the quality of content, the time of publishing works is also crucial. So, how to set the time for Xiaohongshu to publish works? 1. How to set the time for publishing works on Xiaohongshu? 1. Understand the active time of users. First, it is necessary to clarify the active time of Xiaohongshu users. Generally speaking, 8 pm to 10 pm and weekend afternoons are the times when user activity is high. However, this time period will also vary depending on factors such as audience group and geography. Therefore, in order to better grasp the active period of users, it is recommended to conduct a more detailed analysis of the behavioral habits of different groups. By understanding users’ lives

Revealed secrets of cell phone format recovery methods (mobile phone malfunction? Don't worry) Revealed secrets of cell phone format recovery methods (mobile phone malfunction? Don't worry) May 04, 2024 pm 06:01 PM

Nowadays, we will inevitably encounter some problems such as being unable to turn on the phone or lagging, such as system crash, but during use, mobile phones have become an indispensable part of our lives. We are often at a loss, and sometimes, there are no solutions to these problems. To help you solve cell phone problems, this article will introduce you to some methods of cell phone format recovery and restore your phone to normal operation. Back up data - protect important information, such as photos and contacts, from being lost during the formatting process. Before formatting your phone, the first thing to consider is to back up important data and files on your phone. To ensure data security, or choose to transfer files to a cloud storage service, you can back it up by connecting to a computer. Use the system's built-in recovery function - simple

Will formatting a laptop make it faster? Will formatting a laptop make it faster? Feb 12, 2024 pm 11:54 PM

Will formatting a laptop make it faster? If you want to format your Windows laptop but want to know if it will make it faster, this article will help you know the right answer to this question. Will formatting a laptop make it faster? There are many reasons why users format their Windows laptops. But the most common reason is slow performance or speed of your laptop. Formatting a laptop will completely delete all data stored on the C drive or the hard drive partition where Windows operating system is installed. Therefore, every user will think twice before taking this step, especially when it comes to the performance of the laptop. This article will help you understand whether formatting your laptop will speed it up. Formatting your laptop helps

Detailed explanation of Linux file time viewing techniques Detailed explanation of Linux file time viewing techniques Feb 21, 2024 pm 01:15 PM

Detailed explanation of Linux file time viewing techniques In Linux systems, file time information is very important for file management and tracking changes. The Linux system records file change information through three main time attributes, namely access time (atime), modification time (mtime) and change time (ctime). This article details how to view and manage this file time information, and provides specific code examples. 1. Check the file time information by using the ls command with the parameter -l to list the files.

See all articles