Skip to Content
JavaScript 经典实例:第三版
book

JavaScript 经典实例:第三版

by Adam D. Scott, Matthew MacDonald, Shelley Powers
September 2022
Intermediate to advanced
585 pages
8h 17m
Chinese
China Electric Power Press Ltd.
Content preview from JavaScript 经典实例:第三版
92
4
日期
JavaScript
提供的日期功能特别丰富,包装在有点过时的
Date
对象中。你会发现,
Date
对象有一些怪异的行为和隐藏的陷阱,例如月份从
0
开始,以及根据当前计算
机的区域设置解析年份信息。不过,一旦你学会绕开这些绊脚石,就能完成很多常
见的操作,例如计算两个日期之间相差的天数、格式化要显示的日期,以及对事件
计时。
4.1
获取当前日期和时间
4.1.1
问题
你需要获取当前日期或时间。
4.1.2
方案
JavaScript
内置
Date
对象,为处理日期信息提供了很好的支持(还为日期计算提供
了一定的支持)。新建的
Date
对象自动填充当前日期和时间,甚至包括最近的毫秒。
const
today =
new
Date();
日期
93
现在,只需从你创建的
Date
对象中提取所需的信息。为此,
Date
象提供了非常
多的方法。表
4-1
列出一些最重要的方法。注意,不同的方法使用的计数方式并不
完全相同。月份和工作日从
0
开始计数,而日从
1
开始计数。
4
-
1
:获取日期信息的方法
方法
获取
可能的值
getFullYear()
年份
一个四位数
例如
2021
getMonth()
月数
0
11
0
表示一月
getDate()
一个月中的某一天
1
31
getDay()
一周中的某一天
0
6
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

JavaScript Patterns

JavaScript Patterns

Stoyan Stefanov
JavaScript

JavaScript

David Flanagan
JavaScript

JavaScript

T. J. Crowder

Publisher Resources

ISBN: 9787519869601