search

Home  >  Q&A  >  body text

javascript - How to get the server time like new Date() gets the current time?

let sd = 1498482000000;

let serverDate = () => new Date() > sd ? (
    new Date() - (new Date() - sd)
) : (
    new Date() + (sd - new Date())
)

console.log(serverDate()) // 1498482000000
迷茫迷茫2712 days ago539

reply all(1)I'll reply

  • 巴扎黑

    巴扎黑2017-06-28 09:29:55

    1. Every time new Date() will get a different value, and the calculation will take time, it is recommended to use now cache: const now = new Date()

    2. now - (now - sd), the expansion is now - now + sd, that is, now + (sd - now), so the expressions of the two branches are equivalent, there is no need to write them at all Branch

    3. Finally it can be omitted into one sentence: new Date(sd) is the server time, why bother so much

    reply
    0
  • Cancelreply