skip to Main Content

I’m trying to mimmick a temporal API from thee TC39 proposal in Rust and have two internal implementations: one that uses the standard library and one that uses JavaScript (for the browser). It hides other dependencies that might make life easier when mimmicking the proposal.

I’m trying to implement the Instant type and mimmick new Temporal.Instant(epochNanoseconds) as temporal::Instant::from_epoch(), but for one case, I’m using SystemTime from Rust inside my Instant (which doesn’t work in the browser), and for the browser case, I’m using epoch milliseconds inside (Date.now() for instance returns epoch milliseconds).

For non-browser platforms, I can add the given epoch duration to std::time::SystemTime::UNIX_EPOCH, but I found nothing similiar to that for the browser. Do I’ve to use a constant myself then?

2

Answers


  1. Javascript uses milliseconds, but looks like this temporal uses nanoseconds so all we need to do is divide by 1000000.

    Now nanoseconds as time is not going to fit into Javascript Number, so we need to use BigInts for this.

    Below is an example.

    const turnOfTheCentury = -2208988800000000000n;
    
    function convertToMsTime(t) {
      return Number(t / 1000000n);
    }
    
    console.log(new Date(convertToMsTime(turnOfTheCentury)));
    Login or Signup to reply.
  2. The std::time::UNIX_EPOCH constant of Rust, is just 0 in JavaScript — you pass it as argument to the Date constructor to get it as a Date object:

    new Date(0)
    

    Pass any other number of milliseconds as argument to get an offset from that anchor date (positive or negative). See mdn docs on the Date constructor, specifically the value argument.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search