To work with date and time in JavaScript, Date objects are used.
Creature
To create a new object of type Date
use one of the syntaxes:
-
new Date()
- Creates a
Date
object with the current date and time: -
new Date(milliseconds)
- Creates a
Date
object, the value of which is equal to the number of milliseconds (1/1000 seconds) that have elapsed since January 1, 1970 GMT + 0. -
new Date(datestring)
- If the only argument is a string, use the
Date.parse
call to parse it. -
new Date(year, month, date, hours, minutes, seconds, ms)
- The date can be created using components in the local time zone. For this format, only the first two arguments are required. Missing parameters, starting with
hours
are considered to be zero, and date
- ones. Note that the year of the year
must be 4 digits, and the month
counted from zero 0. For example:
new Date(2011, 0, 1, 0, 0, 0, 0); |
The date is set to milliseconds:
Importance: 5
Date in the local time zone is created using new Date
.
Months start from zero, so February is number 1. Parameters can be specified up to minutes:
[Open task in new window]
Receiving date components
The following methods are used to access the date-time components of a Date object:
-
getFullYear()
- Get year (from 4 digits)
-
getMonth()
- Get the month, from 0 to 11 .
-
getDate()
- Get the date of the month, from 1 to 31.
-
getHours(), getMinutes(), getSeconds(), getMilliseconds()
- Get the relevant components.
Some browsers implement the nonstandard getYear()
method. Somewhere he returns only two digits from the year, about four. One way or another, this method is not in the JavaScript standard. Do not use it. To get the year there is getFullYear()
.
Additionally, you can get the day of the week:
-
getDay()
- Get the number of the day in the week. The week in JavaScript starts on Sunday, so the result will be a number from 0 (Sunday) to 6 (Saturday) .
All the methods listed above return the result for the local time zone.
There are also UTC variants of these methods that return the day, month, year, etc. for the GMT + 0 (UTC) zone: getUTCFullYear()
, getUTCMonth()
, getUTCDay()
. That is, immediately after "get"
inserted "UTC"
.
If your local time is shifted relative to UTC, then the following code will show different clocks:
In addition to those described above, there are two special methods without a UTC option:
-
getTime()
- Returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. This is the same number used in the constructor
new Date(milliseconds)
. -
getTimezoneOffset()
- Returns the difference between local and UTC time, in minutes.
Importance: 5
The getDay()
method allows you to get the number of the day of the week, starting from Sunday.
We write the names of the days of the week in the array so that you can get them by the number:
[Open task in new window]
Importance: 5
The solution is to use the built-in getDay
function. It fully fits our goals, but for Sunday it returns 0 instead of 7:
If it is more convenient that the day of the week starts from zero, then you can return in the day - 1
function day - 1
, then the days will be from 0 (mon) to 6 (sun).
[Open task in new window]
Installing date components
The following methods allow you to set date and time components:
-
setFullYear(year [, month, date])
-
setMonth(month [, date])
-
setDate(date)
-
setHours(hour [, min, sec, ms])
-
setMinutes(min [, sec, ms])
-
setSeconds(sec [, ms])
-
setMilliseconds(ms)
-
setTime(milliseconds)
(sets the entire date in milliseconds from 01/01/1970 UTC)
All of them, except setTime()
, also have a UTC-version, for example: setUTCHours()
.
As you can see, some methods can set several date components at the same time, in particular, setHours
. Moreover, if a component is not specified, it does not change. For example:
Auto Date Correction
Autocorrection is a very convenient property of Date
objects. It lies in the fact that you can install obviously incorrect components (for example, January 32), and the object corrects itself.
Incorrect date components are automatically distributed to the rest.
For example, you need to increase by 2 days the date "February 28, 2011". It may be that it will be March 2, and maybe March 1, if the year is a leap year. But we don’t need to think about all this. Just add two days. The rest will make Date
:
It is also used to obtain a date that is distant from the time available. For example, we get a date for 70 seconds greater than the current:
You can install and zero, and even negative components. For example:
Importance: 4
Create the current date and subtract 100 days:
The Date
object auto-corrects itself and returns the correct result.
Note the array with the names of the days of the week. “Zero” day - Sunday.
[Open task in new window]
Importance: 5
Create a date from the next month, but the day is not the first, but “zero” (ie, the previous one):
[Open task in new window]
Conversion to number, date difference
When a Date
object is used in a numeric context, it is converted to the number of milliseconds:
An important side effect: dates can be subtracted, the result of subtracting Date
objects is their temporary difference, in milliseconds .
This is used to measure time:
Importance: 5
First part.
For output, it is enough to generate the date
corresponding to the beginning of the day, i.e. “Today” 00 hours 00 minutes 00 seconds.
The difference between the current date and the beginning of the day is the number of milliseconds since the beginning of the day. It can be easily translated into seconds:
The second part of
To get the seconds remaining until the end of the day, you need to subtract the current time from “tomorrow 00h 00min 00s”.
To generate tomorrow, you need to increase the current day by 1:
[Open task in new window]
Benchmarking
Suppose we have several solutions to the problem, each is described by a function.
How to find out which one is faster?
For example, take two functions that round the number:
1 | function floorMath(x) { |
To measure which one is faster, you cannot run floorMath
once, floorXor
once and measure the difference. One-time start is unreliable, any mini-disturbance will distort the result.
For proper benchmarking, the function is run many times so that the test itself takes substantial time. This will minimize interference. A complex function can be run 100 times, a simple one - 1000 times ...
We measure which of the rounding functions are faster:
Depending on the browser, both floorXor
and floorMath
may be faster.
Imagine - during the first benchmarking bench(floorMath)
computer did something important in parallel (all of a sudden) and it took up resources, and during the second one it stopped. Real situation? Of course real, especially on modern OS.
Much more reliable results can be obtained, the entire package of tests can be banished many times.
Formatting
Date
-embedded formatting methods are rarely used, and mostly for debugging.
-
toString()
, toDateString()
, toTimeString()
- Return a standard string representation, not specified in the standard, but dependent on the browser. The only requirement is human readability. The
toString
method returns the entire date, toDateString()
and toTimeString()
- only the date and time, respectively. -
toLocaleString()
, toLocaleDateString()
, toLocaleTimeString()
- The same, but the string should be based on the local settings and the visitor’s language.
-
toUTCString()
- Same as
toString()
, but the date is in UTC. -
toISOString()
- Returns the date in ISO format. Details of the format will be further. Supported by modern browsers, not supported by IE <9.
Built-in Date
formatting methods do not allow specifying a custom format.
Therefore, as a rule, any output, except debug, is formatted by its own, and not by a built-in function.
Importance: 3
Get the components one by one.
- The day can be obtained as
date.getDate()
. If necessary, add a leading zero: -
date.getMonth()
return the month starting at zero. Increase it by 1: var mm = date.getMonth() + 1; |
-
date.getFullYear()
will return the year in 4-digit format. To make it two-digit, use the remainder operator '%'
: var yy = date.getFullYear() % 100; |
Note that the year, like other components, may need to be supplemented with a zero to the left, and it is possible that yy == 0
(for example, 2000). When added to the line 0+'0' == '00'
, so that will be all right.
Full code:
[Open task in new window]
Importance: 4
In order to find out the time from date
to the current moment - use the subtraction of dates.
[Open task in new window]
Parsing String, Date.parse
All modern browsers, including IE9 +, understand dates in the simplified ISO 8601 Extended format.
This format looks like this: YYYY-MM-DDTHH:mm:ss.sssZ
. To separate the date and time, it uses the symbol 'T'
. The 'Z'
indicates the (optional) time zone - it may be absent, then the UTC zone, or the z
character may also be UTC, or a zone in the format +-hh:mm
.
Simplified options are also possible, for example:
The
Date.parse(str)
method parses the string
str
in this format and returns the corresponding number of milliseconds. If this is not possible,
Date.parse
returns
NaN
.
At the time of writing, some browsers (Safari) perceived the format without 'Z'
as a date in the local timezone (according to the UTC standard), so the example below it does not work correctly:
With a timezone of -07 -07:00 GMT
at the end, all modern browsers work correctly:
Prior to the introduction of the EcmaScript 5 specification, the format was not standardized, and browsers, including IE8-, had their own date formats. Partially, these formats overlap.
For example, the code below works everywhere, including older IE:
You can also read about old IE formats in the documentation for the MSDN method Date.parse.
Of course, now it is better to use the modern format, if the goal is modern browsers, and if IE8- is additionally needed, then either transfer the dates in milliseconds, not strings, or add an es5-shim type library that adds Date.parse
to old IE.
Total
- Date and time are represented in JavaScript by one object: Date. It is impossible to create "only time", it should be with the date. A list of
Date
methods can be found in the Date
or higher reference. - The
Date
object is convenient because it is auto-corrected. Thanks to it it is easy to shift dates. -
Date
objects can be subtracted, the result is the difference in ms.
Comments
To leave a comment
Scripting client side JavaScript, jqvery, BackBone
Terms: Scripting client side JavaScript, jqvery, BackBone