js-temporal / proposal-temporal-v2

Future additions to Temporal
MIT License
24 stars 1 forks source link

fractionalSecond(s) property #10

Open ptomato opened 3 years ago

ptomato commented 3 years ago

Summary of https://github.com/tc39/proposal-temporal/issues/888:

It could be convenient to offer a fractionalSecond or fractionalSeconds property on PlainTime, PlainDateTime, ZonedDateTime, and Duration. The value would be equal to millisecond / 1e3 + microsecond / 1e6 + nanosecond / 1e9.

Advantages:

millisecond / 1e3 + microsecond / 1e6 + nanosecond / 1e9 is a reasonably common operation, and providing it in Temporal would reduce the chances of carelessly getting the exponents wrong.

It could be useful for customized formatting, or for validation (e.g. pdt.fractionalSecond === 0).

Concerns:

The returned value wouldn't be exactly representable as a JS number, which could lead to unwanted effects. An alternative might be to give an integer number of nanoseconds, equal to millisecond * 1e6 + microsecond * 1e3 + nanosecond.

Prior art:

TBD

Constraints / corner cases:

TBD

justingrant commented 3 years ago

Here's a Temporal V1 solution that minimizes the accumulation of floating-point errors by ensuring that there's no floating-point operations performed on an already-non-integer number:

function fractionalSeconds(d) {
  return (d.milliseconds * 1e6 + d.microseconds * 1e3 + d.nanoseconds) / 1e9;
}