# JavaScript

```javascript
var date1 = new Date('December 17, 1995 03:24:00');
// Sun Dec 17 1995 03:24:00 GMT...

var date2 = new Date('1995-12-17T03:24:00');
// Sun Dec 17 1995 03:24:00 GMT...

console.log(date1 === date2);
// expected output: false;

console.log(date1 - date2);
// expected output: 0

```

## Syntax

```javascript
new Date();
new Date(value);
new Date(dateString);
new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);
```

{% hint style="info" %}
**Note:** JavaScript `Date` objects can only be instantiated by calling JavaScript `Date` as a constructor: calling it as a regular function (i.e. without the [`new`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new)operator) will return a string rather than a `Date` object; unlike other JavaScript object types, JavaScript `Date` objects have no literal syntax.
{% endhint %}

#### Parameters

{% hint style="info" %}
**Note:** The argument `monthIndex` is 0-based. This means that `January = 0` and `December = 11`.
{% endhint %}

{% hint style="info" %}
**Note:** Where `Date` is called as a constructor with more than one argument, if values are greater than their logical range (e.g. 13 is provided as the month value or 70 for the minute value), the adjacent value will be adjusted. E.g. `new Date(2013, 13, 1)` is equivalent to `new Date(2014, 1, 1)`, both create a date for `2014-02-01` (note that the month is 0-based). Similarly for other values: `new Date(2013, 2, 1, 0, 70)` is equivalent to `new Date(2013, 2, 1, 1, 10)` which both create a date for `2013-03-01T01:10:00`.
{% endhint %}

{% hint style="info" %}
**Note:** Where `Date` is called as a constructor with more than one argument, the specified arguments represent local time. If UTC is desired, use `new Date(`[`Date.UTC(...)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC)) with the same arguments.
{% endhint %}

`value`Integer value representing the number of milliseconds since January 1, 1970, 00:00:00 UTC, with leap seconds ignored (Unix Epoch; but consider that most Unix timestamp functions count in seconds).

`dateString`String value representing a date. The string should be in a format recognised by the [`Date.parse()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse) method ([IETF-compliant RFC 2822 timestamps](http://tools.ietf.org/html/rfc2822#page-14) and also a [version of ISO8601](http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15)).

{% hint style="info" %}
**Note:** parsing of date strings with the `Date` constructor (and `Date.parse`, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.
{% endhint %}

`year`Integer value representing the year. Values from 0 to 99 map to the years 1900 to 1999. See the [example below](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Two_digit_years_map_to_1900_-_1999).

`monthIndex`Integer value representing the month, beginning with 0 for January to 11 for December.

`day`Optional. Integer value representing the day of the month.

`hours`Optional. Integer value representing the hour of the day.

`minutes`Optional. Integer value representing the minute segment of a time.

`seconds`Optional. Integer value representing the second segment of a time.

`milliseconds`Optional. Integer value representing the millisecond segment of a time.

## Description

* If no arguments are provided, the constructor creates a JavaScript `Date` object for the current date and time according to system settings for timezone offset.
* If at least two arguments are supplied, missing arguments are either set to 1 (if the day is missing) or 0 for all others.
* The JavaScript date is based on a time value that is milliseconds since midnight January 1, 1970, UTC. A day holds 86,400,000 milliseconds. The JavaScript `Date`object range is -100,000,000 days to 100,000,000 days relative to January 1, 1970 UTC.
* The JavaScript `Date` object provides uniform behavior across platforms. The time value can be passed between systems to create a date that represents the same moment in time.
* The JavaScript `Date` object supports a number of UTC (universal) methods, as well as local time methods. UTC, also known as Greenwich Mean Time (GMT), refers to the time as set by the World Time Standard. The local time is the time known to the computer where JavaScript is executed.
* Invoking JavaScript `Date` as a function (i.e., without the [`new`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new) operator) will return a string representing the current date and time.

### Properties <a href="#properties" id="properties"></a>

[`Date.prototype`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/prototype)Allows the addition of properties to a JavaScript `Date` object.`Date.length`The value of&#x20;

`Date.length` is 7. This is the number of arguments handled by the constructor.

## Examples

#### Several ways to create a `Date` object <a href="#several_ways_to_create_a_date_object" id="several_ways_to_create_a_date_object"></a>

The following examples show several ways to create JavaScript dates:

{% hint style="info" %}
**Note:** parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.
{% endhint %}

```javascript
var today = new Date();
var birthday = new Date('December 17, 1995 03:24:00');
var birthday = new Date('1995-12-17T03:24:00');
var birthday = new Date(1995, 11, 17);
var birthday = new Date(1995, 11, 17, 3, 24, 0);
```

#### Two digit years map to 1900 - 1999 <a href="#two_digit_years_map_to_1900_-_1999" id="two_digit_years_map_to_1900_-_1999"></a>

In order to create and get dates between the years 0 and 99 the [`Date.prototype.setFullYear()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setFullYear) and [`Date.prototype.getFullYear()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getFullYear) methods should be used.

```javascript
var date = new Date(98, 1); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT)

// Deprecated method, 98 maps to 1998 here as well
date.setYear(98);           // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT)

date.setFullYear(98);       // Sat Feb 01 0098 00:00:00 GMT+0000 (BST)
```

#### Calculating elapsed time <a href="#calculating_elapsed_time" id="calculating_elapsed_time"></a>

The following examples show how to determine the elapsed time between two JavaScript dates in milliseconds.

Due to the differing lengths of days (due to daylight saving changeover), months and years, expressing elapsed time in units greater than hours, minutes and seconds requires addressing a number of issues and should be thoroughly researched before being attempted.

```javascript
// using Date objects
var start = Date.now();

// the event to time goes here:
doSomethingForALongTime();
var end = Date.now();
var elapsed = end - start; // elapsed time in milliseconds
```

```javascript
// using built-in methods
var start = new Date();

// the event to time goes here:
doSomethingForALongTime();
var end = new Date();
var elapsed = end.getTime() - start.getTime(); // elapsed time in milliseconds
```

```javascript
// to test a function and get back its return
function printElapsedTime(fTest) {
  var nStartTime = Date.now(),
      vReturn = fTest(),
      nEndTime = Date.now();

  console.log('Elapsed time: ' + String(nEndTime - nStartTime) + ' milliseconds');
  return vReturn;
}

var yourFunctionReturn = printElapsedTime(yourFunction);
```

{% hint style="info" %}
**Note:** In browsers that support the [Web Performance API](https://developer.mozilla.org/en-US/docs/Web/API/Window/performance)'s high-resolution time feature, [`Performance.now()`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/now) can provide more reliable and precise measurements of elapsed time than [`Date.now()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now).
{% endhint %}

#### Get the number of seconds since Unix Epoch <a href="#get_the_number_of_seconds_since_unix_epoch" id="get_the_number_of_seconds_since_unix_epoch"></a>

```javascript
var seconds = Math.floor(Date.now() / 1000);
```

In this case it's important to return only a whole number (so a simple division won't do), and also to only return actually elapsed seconds (that's why this code uses [`Math.floor()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor) and not [`Math.round()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round)).

## References

{% embed url="<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date>" %}

## Contributors to this page

Uros Durdevic
