You get a bonus - 1 coin for daily activity. Now you have 1 coin

Date and time

Lecture




  1. Creature
  2. Receiving date components
  3. Installing date components
    1. Auto Date Correction
    2. Conversion to number, date difference
    3. Benchmarking
  4. Formatting
    1. Parsing String, Date.parse
  5. Total

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:
1 var now = new Date();
2 alert(now);
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.
1 // 24 часа после 01.01.1970 GMT+0
2 var Jan02_1970 = new Date(3600*24*1000);
3 alert( Jan02_1970 );
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) // 1 января 2011, 00:00:00 в местной временной зоне
new Date(2011, 0) // то же самое, date по умолчанию равно 1
new Date(2011, 0, 1, 0, 0, 0, 0); // то же самое

The date is set to milliseconds:

1 var d = new Date(2011, 0, 1, 2, 3, 4, 567);
2 alert(d); // 1.01.2011, 02:03:04.567

Importance: 5

Create a Date object for the date: February 20, 2012, 3 hours 12 minutes.

The time zone is local. Display it on the screen.

Decision

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:

1 var d = new Date(2012, 1, 20, 3, 12);
2 alert(d);

[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.

Outdated getYear()

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:

1 var date = new Date();
2
3 alert( date.getHours() ); // час в вашей зоне для даты date
4 alert( date.getUTCHours() ); // час в зоне GMT+0 для даты date

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.

1 alert( new Date().getTimezoneOffset() ); // Для GMT-1 выведет 60

Importance: 5

Create a function getWeekDay(date) , which displays the current day of the week in the short format “mon”, “tue”, ... “sun”.

For example:

var date = new Date(2012,0,3); // 3 января 2012
alert( getWeekDay(date) ); // Должно вывести 'вт'

Decision

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:

1 function getWeekDay(date) {
2    var days = [ 'вс' , 'пн' , 'вт' , 'ср' , 'чт' , 'пт' , 'сб' ] ;
3
4    return days[ date.getDay() ];
5 }
6
7 var date = new Date(2012,0,3); // 3 января 2012
8 alert( getWeekDay(date) ); // 'вт'

[Open task in new window]

Importance: 5

Write a function, getLocalDay(date) which returns the day of the week for the date date .

The day must be returned in European numbering, i.e. Monday is number 1, Tuesday is number 2, ..., Sunday is number 7.

var date = new Date(2012, 0, 3); // 3 янв 2012
alert( getLocalDay(date) ); // вторник, выведет 2

Decision

The solution is to use the built-in getDay function. It fully fits our goals, but for Sunday it returns 0 instead of 7:

01 function getLocalDay(date) {
02
03    var day = date.getDay();
04
05    if ( day == 0 ) { // день 0 становится 7
06      day = 7;
07    }
08   
09    return day;
10 }
11
12 alert( getLocalDay( new Date(2012,0,3)) ); // 2

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:

1 var today = new Date;
2
3 today.setHours(0);
4 alert( today ); // сегодня, но час изменён на 0
5
6 today.setHours(0, 0, 0, 0);
7 alert (today ); // сегодня, ровно 00:00:00.

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.

1 var d = new Date(2013, 0, 32 ); // 32 января 2013 ?!?
2 alert(d); // ... это 1 февраля 2013!

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 :

1 var d = new Date(2011, 1, 28);
2 d.setDate( d.getDate() + 2 );
3
4 alert(d); // 2 марта, 2011

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:

1 var d = new Date();
2 d.setSeconds( d.getSeconds()+70);
3
4 alert(d); // выведет корректную дату

You can install and zero, and even negative components. For example:

1 var d = new Date;
2
3 d.setDate(1); // поставить первое число месяца
4 alert(d);
5
6 d.setDate(0); // нулевого числа нет, будет последнее число предыдущего месяца
7 alert(d);

1 var d = new Date;
2
3 d.setDate(-1); // предпоследнее число предыдущего месяца
4 alert(d);

Importance: 4

What day of the month was 100 days ago? What day of the week?

Use JavaScript to display this information. Day of the week print two-letter form, i.e. one value from (Mon, Tue, Wed, ..., Sun).

Decision

Create the current date and subtract 100 days:

1 var d = new Date;
2 d.setDate( d.getDate() - 100 );
3
4 alert( d.getDate() );
5
6 var dayNames = [ 'вс' , 'пн' , 'вт' , 'ср' , 'чт' , 'пт' , 'сб' ];
7 alert( dayNames[d.getDay()] );

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

Write the function getLastDayInMonth(year, month) , which returns the last day of the month.

Options:

  • year - 4-digit year, for example 2012.
  • month - month from 0 to 11.

For example, getLastDayInMonth(2012, 1) = 29 (leap year, February).

Decision

Create a date from the next month, but the day is not the first, but “zero” (ie, the previous one):

1 function getLastDayOfMonth(year, month) {
2    var date = new Date(year, month+1, 0);
3    return date.getDate();
4 }
5
6 alert( getLastDayOfMonth(2012, 1) ); // 29

[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:

1 alert( + new Date ) // +date то же самое, что: +date.valueOf()

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:

01 var start = new Date; // засекли время
02
03 // что-то сделать
04 for ( var i=0; i<100000; i++) {
05    var doSomething = i*i*i;
06 }
07
08 var end = new Date; // конец измерения
09
10 alert( "Цикл занял " + (end-start) + " ms" );

Importance: 5

Write the code that displays:

  1. How many seconds have passed since the beginning of today.
  2. How much is left until the end of the day.

The script should work any day, i.e. there should not be a specific value of today's date.

Decision

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:

1 var now = new Date();
2
3 // создать объект из текущей даты, без часов-минут-секунд
4 var today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
5
6 var diff = now - today; // разница в миллисекундах
7 alert( Math.round(diff / 1000) ); // перевести в секунды

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:

1 var now = new Date();
2
3 // создать объект из даты, без часов-минут-секунд
4 var tomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate()+1 );
5
6 var diff = tomorrow - now; // разница в миллисекундах
7 alert( Math.round(diff / 1000) ); // перевести в секунды

[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) {
2    return Math.floor(x);
3 }
4
5 function floorXor(x) {
6    return x^0; // побитовое исключающее ИЛИ (XOR) всегда округляет число
7 }

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:

01 function floorMath(x) { return Math.floor(x); } Math.floor(x); }
02 function floorXor(x) { return x^0; } x^0; }
03
04 function bench(f) {
05    var date = new Date();
06    for ( var i=0.5; i<1000000; i++) f(i);
07    return new Date() - date;
08 }
09
10 alert( 'Время floorMath: ' + bench(floorMath) + 'мс' );
11 alert( 'Время floorXor: ' + bench(floorXor) + 'мс' );

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.

01 function floorMath(x) { return Math.floor(x); } Math.floor(x); }
02 function floorXor(x) { return x^0; } x^0; }
03
04 function bench(f) {
05    var date = new Date();
06    for ( var i=0.5; i<100000; i++) f(i);
07    return new Date() - date;
08 }
09
10 var timeMath = 0, timeXor = 0;
11 for ( var i=0; i<100; i++) {
12    timeMath += bench(floorMath);
13    timeXor += bench(floorXor);
14 }
15
16 alert( 'Время floorMath: ' + timeMath + 'мс' );
17 alert( 'Время floorXor: ' +timeXor + 'мс' );

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.
1 var d = new Date();
2
3 alert( d.toString() ); // вывод, похожий на 'Wed Jan 26 2011 16:40:50 GMT+0300'
toLocaleString() , toLocaleDateString() , toLocaleTimeString()
The same, but the string should be based on the local settings and the visitor’s language.
1 var d = new Date();
2
3 alert( d.toLocaleString() ); // дата на языке посетителя
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.

1 var d = new Date();
2
3 alert( d.toISOString() ); // вывод, похожий на '2011-01-26T13:51:50.417Z'

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

Write the function formatDate(date) , which displays the date date in the format дд.мм.гг :

For example:

var d = new Date(2011, 0, 30); // 30 января 2011
alert( formatDate(d) ); // '30.01.11'

PS Please note that leading zeros must be present, that is, January 1, 2011 should be 1/1/11, not 1.1.11.

Decision

Get the components one by one.

  1. The day can be obtained as date.getDate() . If necessary, add a leading zero:
    var dd = date.getDate();
    if (dd<10) dd= '0' +dd;
  2. date.getMonth() return the month starting at zero. Increase it by 1:
    var mm = date.getMonth() + 1; // месяц 1-12
    if (mm<10) mm= '0' +mm;
  3. date.getFullYear() will return the year in 4-digit format. To make it two-digit, use the remainder operator '%' :
    var yy = date.getFullYear() % 100;
    if (yy<10) yy= '0' +yy;
    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:

01 function formatDate(date) {
02
03    var dd = date.getDate()
04    if ( dd < 10 ) dd = '0' + dd;
05
06    var mm = date.getMonth()+1
07    if ( mm < 10 ) mm = '0' + mm;
08
09    var yy = date.getFullYear() % 100;
10    if ( yy < 10 ) yy = '0' + yy;
11
12    return dd+ '.' +mm+ '.' +yy;
13 }
14
15 var d = new Date(2011, 0, 30); // 30 Jan 2011
16 alert( formatDate(d) ); // '30.01.11'

[Open task in new window]

Importance: 4

Write the function formatDate(date) , which formats the date as:

  • If less than a second has passed since date , it returns "только что" .
  • Otherwise, if less than a minute has passed since the date , then "n сек. назад" . "n сек. назад"
  • Otherwise, if less than an hour has passed, then "m мин. назад" . "m мин. назад"
  • Otherwise, the full date in the format "дд.мм.гг чч:мм" .

For example:

1 function formatDate(date) { /* ваш код */ }
2
3 alert( formatDate( new Date( new Date - 1) ) ); // "только что"
4
5 alert( formatDate( new Date( new Date - 30*1000) ) ); // "30 сек. назад"
6
7 alert( formatDate( new Date( new Date- 5*60*1000) ) ); // "5 мин. назад"
8
9 alert( formatDate( new Date( new Date - 86400*1000) ) ); // вчерашняя дата в формате "дд.мм.гг чч:мм"

Decision

In order to find out the time from date to the current moment - use the subtraction of dates.

01 function formatDate(date) {
02    var diff = new Date() - date; // разница в миллисекундах
03   
04    if (diff < 1000) { // прошло менее 1 секунды
05      return 'только что' ;
06    }
07
08    var sec = Math.floor( diff / 1000 ); // округлить diff до секунд
09     
10    if (sec < 60) {
11      return sec + ' сек. назад' ' сек. назад' ;
12    }
13     
14    var min = Math.floor( diff / 60000 ); // округлить diff до минут
15    if (min < 60) {
16      return min + ' мин. назад' ' мин. назад' ;
17    }
18
19    // форматировать дату, с учетом того, что месяцы начинаются с 0
20    var d = date;
21    d = [ '0' +d.getDate(), '0' +(d.getMonth()+1), '' +d.getFullYear(), '0' +d.getHours(), '0' +d.getMinutes() ];
22    for ( var i=0; i<d.length; i++) {
23      d[i] = d[i].slice(-2);
24    }
25
26    return d.slice(0,3).join( '.' )+ ' ' +d.slice(3).join( ':' );
27 }
28
29 alert( formatDate( new Date( new Date - 1) ) ); // только что
30
31 alert( formatDate( new Date( new Date - 30*1000) ) ); // 30 сек. назад
32
33 alert( formatDate( new Date( new Date- 5*60*1000) ) ); // 5 мин. назад
34
35 alert( formatDate( new Date( new Date - 86400*1000) ) ); // вчерашняя дата в формате "дд.мм.гг чч:мм"

[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:

YYYY
YYYY-MM
YYYY-MM-DD
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:

1 var msNoZone = Date.parse( '2012-01-26T13:51:50.417' ); // без зоны, значит UTC
2
3 alert(msNoZone); // 1327571510417 (число миллисекунд)
4
5 var msZ = Date.parse( '2012-01-26T13:51:50.417z' ); // зона z означает UTC
6 alert(msZ == msNoZone); // true, если браузер правильный

With a timezone of -07 -07:00 GMT at the end, all modern browsers work correctly:

1 var ms = Date.parse( '2012-01-26T13:51:50.417-07:00' );
2
3 alert(ms); // 1327611110417 (число миллисекунд)

Date format for IE8-

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:

1 var ms = Date.parse( "January 26, 2011 13:51:50" );
2
3 alert(ms);

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.
created: 2014-10-07
updated: 2021-03-13
132636



Rating 9 of 10. count vote: 2
Are you satisfied?:



Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Scripting client side JavaScript, jqvery, BackBone

Terms: Scripting client side JavaScript, jqvery, BackBone