XDate是一个请谅解的JavaScript的原生Date对象的封装库,提供增强的功能解析,格式化和日期处理。使用起来就和JavaScript自己的对象和方法一样,非常简单。

XDate是一个请谅解的JavaScript的原生Date对象的封装库,提供增强的功能解析,格式化和日期处理。使用起来就和JavaScript自己的对象和方法一样,非常简单。

Download:
Size: 7.2k (3.0k gzipped)
Version: 0.8
Released: Mar 30th, 2013
Dual-licensed under MIT or GPL

使用说明:

 首先在页面中添加 XDate 的 JS 文件

<script src="xdate.js"></script>

  之后就可以了 new 一个日期出来,如

var d = new XDate("2012-9-9");
var c = new XDate(2012, 7, 8);
d.addDays(10);
var a = d.toString("yyyy/MM/dd");

Constructors

new XDate()
使用当前的日期和时间创建一个新的XDate
new XDate(xdate)
创建一个新的XDate从一个xdate对象
new XDate(nativeDate)
创建一个新的XDate从一个指定的日期
new XDate(milliseconds)
通过UTC毫秒数创建一个新的XDate。
new XDate(year, month, date, hours, minutes, seconds, milliseconds)
new XDate(dateString)

Read more about date-string parsing

下面是xDate的常用方法:

Getters

.getFullYear()
Returns the 4-digit year (ex: 2012)
.getMonth()
Returns the month of the year. (0-11)
Value is zero-index, meaning Jan=0, Feb=1, Mar=2, etc.
.getWeek()
Returns the ISO week number of the year. (1-53)
.getDate()
Returns the date of the month. (1-31)
.getDay()
Returns the day-of-week as a number. (0-6)
Sun=0, Mon=1, Tue=2, etc.
.getHours()
Returns the hour of the day. (0-23)
.getMinutes()
Returns the minute of the hour. (0-59)
.getSeconds()
Returns the second of the minute. (0-59)
.getMilliseconds()
Returns the millisecond of the second. (0-999)
.getTime()
Returns the number of milliseconds since the epoch.
.valueOf()
Returns the number of milliseconds since the epoch. Identical to getTime.

Setters

.setFullYear(year, preventOverflow)
year is a 4-digit year
.setMonth(month, preventOverflow)
month is zero-indexed, meaning Jan=0, Feb=1, Mar=2, etc.
.setWeek(week, year)

Moves the xdate to the Monday of the given week with time 00:00:00. The week is represented by a given ISO week number and an optional year. Ifyear is omitted, the xdate's year with be used.

.setDate(date)
Sets the date of the month. (1-31)
.setHours(hours)
Sets the hour of the day. (0-23)
.setMinutes(minutes)
Sets the minute of the hour. (0-59)
.setSeconds(seconds)
Sets the second of the minute. (0-59)
.setMilliseconds(milliseconds)
Sets the millisecond of the second. (0-999)
.setTime(milliseconds)
Sets the number of milliseconds since the epoch.

Setting preventOverflow to true prevents a date from "overflowing" into the next month. Example:

d=newXDate(2011,7,31);// August 31d.setMonth(8);// Septemberd.toString();// October 1st!!! because there are only 30 says in September// let's try this with preventOverflow...d=newXDate(2011,7,31);// August 31d.setMonth(8,true);// Septemberd.toString();// September 30!

Setting preventOverflow to true guarantees the date will be in desired month. It is optional and defaults to false.

Adding

The following methods add or subtract time from the XDate:

.addYears(years, preventOverflow)
.addMonths(months, preventOverflow)
.addWeeks(weeks)
.addDays(days)
.addHours(hours)
.addMinutes(minutes)
.addSeconds(seconds)
.addMilliseconds(milliseconds)

If a value is negative, subtraction will occur. Values may be floating-point numbers.

Please note, these methods directly modify the object. Use clone if you need a copy.

Diffing

The following methods return the amount of time that must be added to the XDate in order to arrive at otherDate.

.diffYears(otherDate)
.diffMonths(otherDate)
.diffWeeks(otherDate)
.diffDays(otherDate)
.diffHours(otherDate)
.diffMinutes(otherDate)
.diffSeconds(otherDate)
.diffMilliseconds(otherDate)

otherDate can be an XDate, a native Date, a milliseconds time, or a date-string.

The results will be positive or negative depending on the ordering of the dates:

varthanksgiving=newXDate(2011,10,24);varchristmas=newXDate(2011,11,25);thanksgiving.diffDays(christmas);// 31christmas.diffDays(thanksgiving);// -31

Also, the result can potentially be a floating-point number:

varjan2011=newXDate(2011,0,1);varjul2012=newXDate(2012,6,1);jan2011.diffYears(jul2012);// 1.5

You'll have to do the rounding or flooring yourself.

Parsing

Date-strings must either be in ISO8601 format or IETF format (like "Mon Sep 05 2011 12:30:00 GMT-0700 (PDT)")

ISO8601 is the preferred format. Examples:

  • "2011-09-05"

  • "2011-09-05T12:30:00"

  • "2011-09-05T12:30:00-07:00"

  • "2011-09-05T12:30:00Z"

Advanced: extending the parser

Formatting

.toString(formatString, settings)
If formatString is not specified, a browser-produced IETF string will be returned. settings can be a name of an available locale or an object that overrides the default locale's settings.
.toUTCString(formatString, settings)
Same as toString but gets its values from the UTC version of the date. As a result, "Z" will be displayed as the timezone.
.toISOString()
Returns an ISO8601 string that has been normalized to UTC. Will have a "Z" timezone indicator. See the native Date's specs for toISOString.
.toDateString()
Same as native Date's toDateString
.toTimeString()
Same as native Date's toTimeString
.toLocaleString()
Same as native Date's toLocaleString
.toLocaleDateString()
Same as native Date's toLocaleDateString
.toLocaleTimeString()
Same as native Date's toLocaleTimeString

formatString can contain any of the following tokens:

fff milliseconds, 3-digits
s seconds
ss seconds, 2-digits
m minutes
mm minutes, 2-digits
h hours, 12-hour clock
hh hours, 12-hour clock, 2-digits
H hours, 24-hour clock
HH hours, 24-hour clock, 2-digits
d date number
dd date number, 2-digits
ddd day name, 3-characters (like "Sun")
dddd day name, full (like "Sunday")
M month number (Jan=1, Feb=2, etc)
MM month number, 2-digits
MMM month name, 3-characters (like "Jan")
MMMM month name, full (like "January")
yy year, 2-digits
yyyy year, 4-digits
t a/p
tt am/pm
T A/P
TT AM/PM
z timezone offset hour (like "-7") or "Z"
zz timezone offset hour, 2-digits (like "-07") or "Z"
zzz timezone offset hour, 2-digits, and minutes (like "-07:00") or "Z"
w ISO week number
ww ISO week number, 2 digits
S day-of-week ordinal (like "st", "nd", "rd")
i ISO8601 format, without a timezone indicator
u ISO8601 format, with a timezone indicator

Example:

vard=newXDate(2012,5,8);d.toString("MMM d, yyyy");// "Jun 8, 2012"d.toString("i");// "2012-06-08T00:00:00"d.toString("u");// "2012-06-08T00:00:00-07:00"

If you want to have literal text in your formatString, enclose it in single quotes:

vard=newXDate(2012,5,8);d.toString("'the month is' MMMM");// "the month is June"

A literal single quote is represented by two consecutive single quotes.

If you want to output text only if certain values are non-zero, enclose your tokens in parenthesis:

newXDate(2011,0,1,6,0).toString('M/d/yy h(:mm)TT');// "1/1/11 6AM"newXDate(2011,0,1,6,30).toString('M/d/yy h(:mm)TT');// "1/1/11 6:30AM"

Advanced:

UTC Methods

The following methods are similar to previously mentioned methods but operate on the UTC values of the date:

.getUTCFullYear()
.getUTCMonth()
.getUTCWeek()
.getUTCDate()
.getUTCDay()
.getUTCHours()
.getUTCMinutes()
.getUTCSeconds()
.getUTCMilliseconds()
.setUTCFullYear(year)
.setUTCMonth(month)
.setUTCWeek(week, year)
.setUTCDate(date)
.setUTCHours(hours)
.setUTCMinutes(minutes)
.setUTCSeconds(seconds)
.setUTCMilliseconds(milliseconds)

UTC Mode

Just like a native Date, an XDate is represented by its number of milliseconds since the epoch. Also like a native Date, methods like getDate and getHours are dependant upon the client computer's timezone.

However, you can remove this reliance on the client computer's timezone and make a UTC date, a date without a timezone. A date in UTC-mode will have all of its "get" methods identical to its "getUTC" methods and won't experience any daylight-savings time.

true argument can be appended to any of the constructors to make an XDate in UTC-mode:

d=newXDate(true);// the current date, in UTC-moded.toString();// "Mon, 24 Oct 2011 08:42:08 GMT"d=newXDate(2012,5,8,true);// values will be interpreted as UTCd.toString();// "Fri, 08 Jun 2012 00:00:00 GMT"d=newXDate('2012-06-08',true);// ambiguous timezone, so will be parsed as UTCd.toString();// "Fri, 08 Jun 2012 00:00:00 GMT"

Here are methods that relate to UTC-mode:

.getUTCMode()
Returns true if the date is in UTC-mode and false otherwise
.setUTCMode(utcMode, doCoercion)
utcMode must be either true or false. If the optional doCoercion parameters is set to true, the underlying millisecond time of the date will be coerced in such a way that methods like getDate and getHours will have the same values before and after the conversion.
.getTimezoneOffset()
Returns the number of minutes from UTC, just like the native Date's getTimezoneOffset. However, if the XDate is in UTC-mode, 0 will be returned.

Please note, these methods directly modify the object. Use clone if you need a copy.

Utilities

.clone()
returns a copy of the XDate
.clearTime()
sets the hours, minutes, seconds, and milliseconds to zero
.valid()
return true if the XDate is a valid date, false otherwise
.toDate()
Returns a conversion to a native Date

The following utilities are members of the XDate class and are not associated with a specific XDate instance:

XDate.getDaysInMonth(year, month)
Returns the number of days in the given month
XDate.parse(dateString)
Parses a date-string and returns milliseconds since the epoch. You'll probably want to use new XDate(dateString) instead.
XDate.now()
Returns the current date, as milliseconds since the epoch. You'll probably want to use new XDate() instead.
XDate.today()
Returns the current date with time cleared, as an XDate object
XDate.UTC(year, month, date, hours, minutes, seconds, milliseconds)
Returns a milliseconds time since the epoch for the given UTC date

Chaining

Many of XDate's methods return a reference to the same XDate object. This allows you to "chain" operations together and makes for more concise code:

d1=newXDate();d2=d1.clone().setUTCMode(true).setDate(1).addMonths(1).addYears(2);

Inconsistencies with Native Date

XDate attempts to be "backwards-compatible" with the native Date object. However, there are two small departures that were made:

If you've never noticed, a native Date object returns it's millisecond value every time there is a "set" method. This is not very helpful. In the same situations, an XDate will return a reference to itself to allow for chaining. This is much more useful, but does not match the way the native Date works.

Also, when a native Date is concatenated with a string (with&n

[Javascript] 轻量级的JavaScript日期处理类库xDate使用指南的更多相关文章

  1. [Javascript] 5个最佳的Javascript日期处理类库

    在大家日常网站开发和web应用开发中,我们往往需要有效的调用Javascript处理日期和时间格式相关的函数,在Javascript中已经包含了部分最基本的内建处理方法. 在大家日常网站开发和web应 ...

  2. Moment.js 超棒Javascript日期处理类库

    Moment.js 不容错过的超棒Javascript日期处理类库 主要特性: 3.2kb超轻量级 独立类库,意味这你不需要倒入一堆js 日期处理支持UNIX 时间戳,String,指定格式的Date ...

  3. 翻译连载 | 第 9 章:递归(下)-《JavaScript轻量级函数式编程》 |《你不知道的JS》姊妹篇

    原文地址:Functional-Light-JS 原文作者:Kyle Simpson-<You-Dont-Know-JS>作者 关于译者:这是一个流淌着沪江血液的纯粹工程:认真,是 HTM ...

  4. 翻译连载 |《你不知道的JS》姊妹篇 |《JavaScript 轻量级函数式编程》- 引言&前言

    原文地址:Functional-Light-JS 原文作者:Kyle Simpson-<You-Dont-Know-JS>作者 译者团队(排名不分先后):阿希.blueken.brucec ...

  5. 翻译连载 | 第 10 章:异步的函数式(上)-《JavaScript轻量级函数式编程》 |《你不知道的JS》姊妹篇

    原文地址:Functional-Light-JS 原文作者:Kyle Simpson-<You-Dont-Know-JS>作者 关于译者:这是一个流淌着沪江血液的纯粹工程:认真,是 HTM ...

  6. 翻译连载 | 第 10 章:异步的函数式(下)-《JavaScript轻量级函数式编程》 |《你不知道的JS》姊妹篇

    原文地址:Functional-Light-JS 原文作者:Kyle Simpson-<You-Dont-Know-JS>作者 关于译者:这是一个流淌着沪江血液的纯粹工程:认真,是 HTM ...

  7. 翻译连载 | 第 11 章:融会贯通 -《JavaScript轻量级函数式编程》 |《你不知道的JS》姊妹篇

    原文地址:Functional-Light-JS 原文作者:Kyle Simpson-<You-Dont-Know-JS>作者 关于译者:这是一个流淌着沪江血液的纯粹工程:认真,是 HTM ...

  8. 翻译连载 | 附录 A:Transducing(上)-《JavaScript轻量级函数式编程》 |《你不知道的JS》姊妹篇

    原文地址:Functional-Light-JS 原文作者:Kyle Simpson-<You-Dont-Know-JS>作者 关于译者:这是一个流淌着沪江血液的纯粹工程:认真,是 HTM ...

  9. 翻译连载 | 附录 A:Transducing(下)-《JavaScript轻量级函数式编程》 |《你不知道的JS》姊妹篇

    原文地址:Functional-Light-JS 原文作者:Kyle Simpson-<You-Dont-Know-JS>作者 关于译者:这是一个流淌着沪江血液的纯粹工程:认真,是 HTM ...

随机推荐

  1. 网页前端状态管理库Redux学习笔记(一)

    最近在博客园上看到关于redux的博文,于是去了解了一下. 这个Js库的思路还是很好的,禁止随意修改状态,只能通过触发事件来修改.中文文档在这里. 前面都很顺利,但是看到异步章节,感觉关于异步说得很乱 ...

  2. 【SQL】BETWEEN操作符

    BETWEEN 操作符在 WHERE 子句中使用,作用是选取介于两个值之间的数据范围. 操作符 BETWEEN ... AND 会选取介于两个值之间的数据范围.这些值可以是数值.文本或者日期. 注意: ...

  3. 三种“BIOS设置光驱第一启动的图解”

    除特殊机器类型一般都是“开机按DEL进入BIOS界面,当然还有AMD主板有按F2的进入” 第一种.AWARD BIOS设置光驱启动方法: 进入Bios界面,选第二项——>回车 选中此项,按PAG ...

  4. ListUtil集合操作常用方法类

    * 集合操作常用方法类. * <p> * * @author 柯 */ public class ListUtil { /** * 判断List不为空,非空返回true,空则返回false ...

  5. python 从给定的URL中提取顶级域名(TLD)

    安装 PyPI的最新稳定版本: pip install tld 或者GitHub的最新稳定版本: pip install https://github.com/barseghyanartur/tld/ ...

  6. Lua循环结构while循环、repeat 循环、for循环_学习笔记03

    Lua循环结构while循环.repeat 循环.for循环 while语法结构 while 循环条件 do 循环体  end --1.输出1到100 index = do print(index) ...

  7. win10家庭版转专业版并激活

    之前重装win10的时候没注意,不小心装成家庭版. 本以为家庭版也没什么,后来发现这对程序员来说造成致命打击. 在系统信息页面底部点击“更改密匙”,输入win10升级产品密匙:VK7JG-NPHTM- ...

  8. 洛谷P1060 开心的金明【dp】

    金明今天很开心,家里购置的新房就要领钥匙了,新房里有一间他自己专用的很宽敞的房间.更让他高兴的是,妈妈昨天对他说:"你的房间需要购买哪些物品,怎么布置,你说了算,只要不超过NN元钱就行&qu ...

  9. [luogu1971 NOI2011] 兔兔与蛋蛋游戏 (二分图博弈)

    传送门 Solution 补一篇二分图博弈 这个博客写的很详细qwq: https://www.cnblogs.com/maijing/p/4703094.html Code //By Menteur ...

  10. (27)Spring Boot Junit单元测试【从零开始学Spring Boot】

    Junit这种老技术,现在又拿出来说,不为别的,某种程度上来说,更是为了要说明它在项目中的重要性. 那么先简单说一下为什么要写测试用例 1. 可以避免测试点的遗漏,为了更好的进行测试,可以提高测试效率 ...