Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[new-ci] Reference for stage 3 temporal #37344

Open
wants to merge 42 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 21 commits
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
27a3784
Reference for stage 3 temporal
Josh-Cena Dec 21, 2024
a477fa3
More description
Josh-Cena Dec 24, 2024
9f50952
Duration docs
Josh-Cena Dec 26, 2024
bd0796c
Fix link
Josh-Cena Dec 26, 2024
fbd0601
Complete Duration docs
Josh-Cena Dec 26, 2024
6ab2afd
Instant docs
Josh-Cena Dec 27, 2024
ef79211
Now docs
Josh-Cena Dec 27, 2024
02295b7
TZ and calendar docs
Josh-Cena Dec 27, 2024
0936403
PlainDate docs
Josh-Cena Dec 29, 2024
889b358
Change ISO format description
Josh-Cena Dec 29, 2024
7ca2b31
ZonedDateTime-specific stuff docs
Josh-Cena Dec 29, 2024
7d9cdfe
PlainMonthDay docs, copy date-related fields to PlainDateTime
Josh-Cena Dec 30, 2024
a0ab015
PlainYearMonth docs
Josh-Cena Dec 30, 2024
f4342cf
PlainTime docs
Josh-Cena Dec 31, 2024
4974d24
Intl docs
Josh-Cena Dec 31, 2024
0a172b6
PlainDateTime docs
Josh-Cena Jan 2, 2025
ac18c5f
ZonedDateTime docs, easy part
Josh-Cena Jan 2, 2025
ac298ef
ZonedDateTime docs... and that shall be all
Josh-Cena Jan 3, 2025
f385d12
Simplifications and fixes
Josh-Cena Jan 3, 2025
49485c0
typo
Josh-Cena Jan 3, 2025
2995aaa
Merge branch 'main' into temporal
Josh-Cena Jan 3, 2025
1324f8d
Apply suggestions from code review
Josh-Cena Jan 5, 2025
44f3f7b
ISO 8601 -> RFC 9557
Josh-Cena Jan 5, 2025
a27aa82
Clarify time zone ID input
Josh-Cena Jan 6, 2025
1ad6603
Time zone ID is required
Josh-Cena Jan 6, 2025
f30c94e
Slight reorg
Josh-Cena Jan 7, 2025
7a86d33
Apply suggestions from code review
Josh-Cena Jan 9, 2025
fc843e3
More feedback
Josh-Cena Jan 9, 2025
cb3ce38
More reviews
Josh-Cena Jan 9, 2025
26c065c
Merge branch 'main' into temporal
fiji-flo Jan 10, 2025
0b7b04d
Reviews
Josh-Cena Jan 10, 2025
ce86a53
Reviews, Temporal.Now
Josh-Cena Jan 10, 2025
e28fc82
Mention precision of Temporal.Now methods
Josh-Cena Jan 10, 2025
6756d76
Reviews, landing pages
Josh-Cena Jan 10, 2025
fc28f6b
Apply suggestions from code review
Josh-Cena Jan 10, 2025
2e7b76a
Time zone / calendar / time components
Josh-Cena Jan 13, 2025
2ebbb0e
Reviews, other constructors
Josh-Cena Jan 14, 2025
0f7231a
Reviews, other constructors, arithmetic, monthCode
Josh-Cena Jan 14, 2025
627cdeb
Merge branch 'main' into temporal
Josh-Cena Jan 14, 2025
bf72961
Update index.md
Josh-Cena Jan 14, 2025
0ca21c0
Update index.md
Josh-Cena Jan 14, 2025
25e1bb1
Update index.md
Josh-Cena Jan 14, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion files/en-us/web/javascript/data_structures/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ Objects are ad-hoc key-value pairs, so they are often used as maps. However, the

### Dates

When representing dates, the best choice is to use the built-in [`Date`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) utility in JavaScript.
When representing dates, JavaScript provides two sets of APIs: the legacy {{jsxref("Date")}} object and the modern {{jsxref("Temporal")}} object. The former has many undesirable design choices and should be avoided in new code if possible. Read the {{jsxref("Temporal")}} reference page for more information.
Josh-Cena marked this conversation as resolved.
Show resolved Hide resolved

### Indexed collections: Arrays and typed Arrays

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1038,16 +1038,16 @@ if the specified object is of the specified object type. The syntax is:
object instanceof objectType
```

where `object` is the object to test against `objectType`, and `objectType` is a constructor representing a type, such as {{jsxref("Date")}} or {{jsxref("Array")}}.
where `object` is the object to test against `objectType`, and `objectType` is a constructor representing a type, such as {{jsxref("Map")}} or {{jsxref("Array")}}.

Use `instanceof` when you need to confirm the type of an object at runtime.
For example, when catching exceptions, you can branch to different exception-handling code depending on the type of exception thrown.

For example, the following code uses `instanceof` to determine whether `theDay` is a `Date` object. Because `theDay` is a `Date` object, the statements in the `if` statement execute.
For example, the following code uses `instanceof` to determine whether `obj` is a `Map` object. Because `obj` is a `Map` object, the statements in the `if` statement execute.
Josh-Cena marked this conversation as resolved.
Show resolved Hide resolved

```js
const theDay = new Date(1995, 12, 17);
if (theDay instanceof Date) {
const obj = new Map();
if (obj instanceof Map) {
// statements to execute
}
```
Expand Down
2 changes: 1 addition & 1 deletion files/en-us/web/javascript/guide/introduction/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ The JavaScript documentation on MDN includes the following:

JavaScript is a cross-platform, object-oriented scripting language used to make webpages interactive (e.g., having complex animations, clickable buttons, popup menus, etc.). There are also more advanced server side versions of JavaScript such as Node.js, which allow you to add more functionality to a website than downloading files (such as realtime collaboration between multiple computers). Inside a host environment (for example, a web browser), JavaScript can be connected to the objects of its environment to provide programmatic control over them.

JavaScript contains a standard library of objects, such as `Array`, `Date`, and `Math`, and a core set of language elements such as operators, control structures, and statements. Core JavaScript can be extended for a variety of purposes by supplementing it with additional objects; for example:
JavaScript contains a standard library of objects, such as `Array`, `Map`, and `Math`, and a core set of language elements such as operators, control structures, and statements. Core JavaScript can be extended for a variety of purposes by supplementing it with additional objects; for example:

- _Client-side JavaScript_ extends the core language by supplying objects to control a browser and its _Document Object Model_ (DOM). For example, client-side extensions allow an application to place elements on an HTML form and respond to user events such as mouse clicks, form input, and page navigation.
- _Server-side JavaScript_ extends the core language by supplying objects relevant to running JavaScript on a server. For example, server-side extensions allow an application to communicate with a database, provide continuity of information from one invocation to another of the application, or perform file manipulations on a server.
Expand Down
3 changes: 3 additions & 0 deletions files/en-us/web/javascript/guide/numbers_and_dates/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,9 @@ Read more about what you can do with BigInt values in the [Expressions and Opera

## Date object

> [!NOTE]
> The `Date` object is now considered legacy and should be avoided in new code. We will update this section with modern alternatives soon.
chrisdavidmills marked this conversation as resolved.
Show resolved Hide resolved

JavaScript does not have a date data type. However, you can use the {{jsxref("Date")}} object and its methods to work with dates and times in your applications. The `Date` object has a large number of methods for setting, getting, and manipulating dates. It does not have any properties.

JavaScript handles dates similarly to Java. The two languages have many of the same date methods, and both languages store dates as the number of milliseconds since midnight at the beginning of January 1, 1970, UTC, with a Unix Timestamp being the number of seconds since the same instant. The instant at the midnight at the beginning of January 1, 1970, UTC is called the [epoch](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date).
Expand Down
2 changes: 1 addition & 1 deletion files/en-us/web/javascript/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ Learn how to program in JavaScript from the ground up with our beginner's tutori
Browse the complete [JavaScript reference](/en-US/docs/Web/JavaScript/Reference) documentation.

- [Standard objects](/en-US/docs/Web/JavaScript/Reference/Global_Objects)
- : Get to know standard built-in objects {{jsxref("Array")}}, {{jsxref("Boolean")}}, {{jsxref("Date")}}, {{jsxref("Error")}}, {{jsxref("Function")}}, {{jsxref("JSON")}}, {{jsxref("Math")}}, {{jsxref("Number")}}, {{jsxref("Object")}}, {{jsxref("RegExp")}}, {{jsxref("String")}}, {{jsxref("Map")}}, {{jsxref("Set")}}, {{jsxref("WeakMap")}}, {{jsxref("WeakSet")}}, and others.
- : Get to know standard built-in objects {{jsxref("Array")}}, {{jsxref("Boolean")}}, {{jsxref("Error")}}, {{jsxref("Function")}}, {{jsxref("JSON")}}, {{jsxref("Math")}}, {{jsxref("Number")}}, {{jsxref("Object")}}, {{jsxref("RegExp")}}, {{jsxref("String")}}, {{jsxref("Map")}}, {{jsxref("Set")}}, {{jsxref("WeakMap")}}, {{jsxref("WeakSet")}}, and others.
Josh-Cena marked this conversation as resolved.
Show resolved Hide resolved
- [Expressions and operators](/en-US/docs/Web/JavaScript/Reference/Operators)
- : Learn more about the behavior of JavaScript's operators {{jsxref("Operators/instanceof", "instanceof")}}, {{jsxref("Operators/typeof", "typeof")}}, {{jsxref("Operators/new", "new")}}, {{jsxref("Operators/this", "this")}}, the [operator precedence](/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence), and more.
- [Statements and declarations](/en-US/docs/Web/JavaScript/Reference/Statements)
Expand Down
2 changes: 1 addition & 1 deletion files/en-us/web/javascript/language_overview/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ Everything else is known as an [Object](/en-US/docs/Web/JavaScript/Data_structur

- {{jsxref("Function")}}
- {{jsxref("Array")}}
- {{jsxref("Date")}}
- {{jsxref("Map")}}
- {{jsxref("RegExp")}}
- {{jsxref("Error")}}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ const instance2 = new DerivedWithConstructor(); // Logs 1

### Using class fields

Class fields cannot depend on arguments of the constructor, so field initializers usually evaluate to the same value for each instance (unless the same expression can evaluate to different values each time, such as {{jsxref("Date.now()")}} or object initializers).
Class fields cannot depend on arguments of the constructor, so field initializers usually evaluate to the same value for each instance (unless the same expression can evaluate to different values each time, such as {{jsxref("Math.random()")}} or object initializers).

```js example-bad
class Person {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ toLocaleString(locales, options)
- `locales` {{optional_inline}}
- : A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [the parameter description on the `Intl` main page](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument).
- `options` {{optional_inline}}
- : An object with configuration properties. For numbers, see {{jsxref("Number.prototype.toLocaleString()")}}; for dates, see {{jsxref("Date.prototype.toLocaleString()")}}.
- : An object with configuration properties. What you can pass here depends on what elements are being converted. For example, for numbers, see {{jsxref("Number.prototype.toLocaleString()")}}.
chrisdavidmills marked this conversation as resolved.
Show resolved Hide resolved

### Return value

Expand All @@ -47,15 +47,7 @@ The `toLocaleString()` method is [generic](/en-US/docs/Web/JavaScript/Reference/

### Using locales and options

The elements of the array are converted to strings using their
`toLocaleString` methods.

- `Object`: {{jsxref("Object.prototype.toLocaleString()")}}
- `Number`: {{jsxref("Number.prototype.toLocaleString()")}}
- `Date`: {{jsxref("Date.prototype.toLocaleString()")}}

Always display the currency for the strings and numbers in the `prices`
array:
The elements of the array are converted to strings using their `toLocaleString` methods. For example, this example implicitly calls the {{jsxref("Number.prototype.toLocaleString()")}} method to always display the currency for the strings and numbers in the `prices` array:
Josh-Cena marked this conversation as resolved.
Show resolved Hide resolved

```js
const prices = ["¥7", 500, 8123, 12];
Expand All @@ -64,8 +56,6 @@ prices.toLocaleString("ja-JP", { style: "currency", currency: "JPY" });
// "¥7,¥500,¥8,123,¥12"
```

For more examples, see also the [`Intl.NumberFormat`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) and [`Intl.DateTimeFormat`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) pages.

### Using toLocaleString() on sparse arrays

`toLocaleString()` treats empty slots the same as `undefined` and produces an extra separator:
Expand Down Expand Up @@ -108,4 +98,4 @@ console.log(Array.prototype.toLocaleString.call(arrayLike));
- {{jsxref("Intl.ListFormat")}}
- {{jsxref("Object.prototype.toLocaleString()")}}
- {{jsxref("Number.prototype.toLocaleString()")}}
- {{jsxref("Date.prototype.toLocaleString()")}}
- {{jsxref("Temporal/PlainDate/toLocaleString", "Temporal.PlainDate.prototype.toLocaleString()")}}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ browser-compat: javascript.builtins.Date
JavaScript **`Date`** objects represent a single moment in time in a platform-independent format. `Date` objects encapsulate an integral number that represents milliseconds since the midnight at the beginning of January 1, 1970, UTC (the _epoch_).

> [!NOTE]
> TC39 is working on [Temporal](https://tc39.es/proposal-temporal/docs/index.html), a new Date/Time API. Read more about it on the [Igalia blog](https://blogs.igalia.com/compilers/2020/06/23/dates-and-times-in-javascript/). It is not yet ready for production use!
> With the introduction of the {{jsxref("Temporal")}} API, the `Date` object is considered a legacy feature. If the [browser compatibility](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal#browser_compatibility) for `Temporal` is acceptable for your application, consider using `Temporal` for new code, and migrating existing code to use `Temporal` instead. We will be writing a usage guide soon!
Josh-Cena marked this conversation as resolved.
Show resolved Hide resolved

## Description

Expand Down Expand Up @@ -284,6 +284,8 @@ These properties are defined on `Date.prototype` and shared by all `Date` instan
- : Returns a string with a locality-sensitive representation of the time portion of this date, based on system settings.
- {{jsxref("Date.prototype.toString()")}}
- : Returns a string representing the specified `Date` object. Overrides the {{jsxref("Object.prototype.toString()")}} method.
- {{jsxref("Date.prototype.toTemporalInstant()")}}
- : Returns a new {{jsxref("Temporal.Instant")}} object with the same {{jsxref("Temporal/Instant/epochMilliseconds", "epochMilliseconds")}} value as this date's [timestamp](#the_epoch_timestamps_and_invalid_date).
- {{jsxref("Date.prototype.toTimeString()")}}
- : Returns the "time" portion of the `Date` as a human-readable string.
- {{jsxref("Date.prototype.toUTCString()")}}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
---
title: Date.prototype.toTemporalInstant()
slug: Web/JavaScript/Reference/Global_Objects/Date/toTemporalInstant
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.toTemporalInstant
---

{{JSRef}}

The **`toTemporalInstant()`** method of {{jsxref("Date")}} instances returns a new {{jsxref("Temporal.Instant")}} object with the same {{jsxref("Temporal/Instant/epochMilliseconds", "epochMilliseconds")}} value as this date's [timestamp](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date).

Use this method to convert legacy `Date` code to the `Temporal` API, then further convert it to other {{jsxref("Temporal")}} classes as necessary.
Josh-Cena marked this conversation as resolved.
Show resolved Hide resolved

## Syntax

```js-nolint
toTemporalInstant()
```

### Parameters

None.

### Return value

A new {{jsxref("Temporal.Instant")}} object with the same {{jsxref("Temporal/Instant/epochMilliseconds", "epochMilliseconds")}} value as this date's timestamp. Its {{jsxref("Temporal/Instant/microsecond", "microsecond")}} and {{jsxref("Temporal/Instant/nanosecond", "nanosecond")}} fields are always `0`.
Josh-Cena marked this conversation as resolved.
Show resolved Hide resolved

## Examples

### Using toTemporalInstant()

```js
const legacyDate = new Date("2021-07-01T12:34:56.789Z");
const instant = legacyDate.toTemporalInstant();

// Further convert it to other objects
const zdt = instant.toZonedDateTimeISO("UTC");
const date = zdt.toPlainDate();
console.log(date.toString()); // 2021-07-01
```

## Specifications

{{Specifications}}

## Browser compatibility

{{Compat}}

## See also

- {{jsxref("Temporal.Instant")}}
- {{jsxref("Temporal.ZonedDateTime")}}
- {{jsxref("Temporal/Instant/fromEpochMilliseconds", "Temporal.Instant.fromEpochMilliseconds()")}}
28 changes: 10 additions & 18 deletions files/en-us/web/javascript/reference/global_objects/eval/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -201,22 +201,22 @@ Simply using indirect eval and forcing strict mode can make the code much better
function looseJsonParse(obj) {
return eval?.(`"use strict";(${obj})`);
}
console.log(looseJsonParse("{ a: 4 - 1, b: function () {}, c: new Date() }"));
console.log(looseJsonParse("{ a: 4 - 1, b: function () {}, c: new Map() }"));
Josh-Cena marked this conversation as resolved.
Show resolved Hide resolved
```

The two code snippets above may seem to work the same way, but they do not; the first one using direct eval suffers from multiple problems.

- It is a great deal slower, due to more scope inspections. Notice `c: new Date()` in the evaluated string. In the indirect eval version, the object is being evaluated in the global scope, so it is safe for the interpreter to assume that `Date` refers to the global `Date()` constructor instead of a local variable called `Date`. However, in the code using direct eval, the interpreter cannot assume this. For example, in the following code, `Date` in the evaluated string doesn't refer to `window.Date()`.
- It is a great deal slower, due to more scope inspections. Notice `c: new Map()` in the evaluated string. In the indirect eval version, the object is being evaluated in the global scope, so it is safe for the interpreter to assume that `Map` refers to the global `Map()` constructor instead of a local variable called `Map`. However, in the code using direct eval, the interpreter cannot assume this. For example, in the following code, `Map` in the evaluated string doesn't refer to `window.Map()`.

```js
function looseJsonParse(obj) {
function Date() {}
class Map {}
return eval(`(${obj})`);
}
console.log(looseJsonParse(`{ a: 4 - 1, b: function () {}, c: new Date() }`));
console.log(looseJsonParse(`{ a: 4 - 1, b: function () {}, c: new Map() }`));
```

Thus, in the `eval()` version of the code, the browser is forced to make the expensive lookup call to check to see if there are any local variables called `Date()`.
Thus, in the `eval()` version of the code, the browser is forced to make the expensive lookup call to check to see if there are any local variables called `Map()`.

- If not using strict mode, `var` declarations within the `eval()` source becomes variables in the surrounding scope. This leads to hard-to-debug issues if the string is acquired from external input, especially if there's an existing variable with the same name.
- Direct eval can read and mutate bindings in the surrounding scope, which may lead to external input corrupting local data.
Expand All @@ -233,21 +233,13 @@ The difference between `eval()` and `Function()` is that the source string passe
The `Function()` constructor is useful if you wish to create local bindings within your eval source, by passing the variables as parameter bindings.

```js
function Date(n) {
return [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday",
][n % 7 || 0];
function add(a, b) {
return a + b;
}
function runCodeWithDateFunction(obj) {
return Function("Date", `"use strict";return (${obj});`)(Date);
function runCodeWithAddFunction(obj) {
return Function("add", `"use strict";return (${obj});`)(add);
}
console.log(runCodeWithDateFunction("Date(5)")); // Saturday
console.log(runCodeWithAddFunction("add(5, 7)")); // 12
```

Both `eval()` and `Function()` implicitly evaluate arbitrary code, and are forbidden in strict [CSP](/en-US/docs/Web/HTTP/CSP) settings. There are also additional safer (and faster!) alternatives to `eval()` or `Function()` for common use-cases.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ These are the base objects representing numbers, dates, and mathematical calcula
- {{jsxref("BigInt")}}
- {{jsxref("Math")}}
- {{jsxref("Date")}}
- {{jsxref("Temporal")}}
chrisdavidmills marked this conversation as resolved.
Show resolved Hide resolved

### Text processing

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,3 +90,4 @@ console.log(new Intl.Collator("sv", { sensitivity: "base" }).compare("ä", "a"))
## See also

- {{jsxref("Intl")}}
- {{jsxref("String.prototype.localeCompare()")}}
Loading
Loading