2

I've been writing a lot of time related code recently, and in various files, I always end up re-defining things like

var SECOND = 1000; var MINUTE = 60 * SECOND;

This gets frustrating quickly. So I'm considering two possibilities:

  1. Getting rid of the constants and instead letting things be inferred from code like 60 * 1000
    • I dislike this option because it's not as human readable
  2. Attaching the constants to a global so they only have to be written in one place
    • I think this is the best way to go, but I'm unsure about the potential consequences of this
  3. I could use a package and import from it
    • This has the same problem that I'm already doing, which would be defining it everywhere over and over

How do you handle this issue or is it something we have to live with?

Side note 1: I am writing this in JavaScript, which is why globals are an option, but I feel like this might still be applicable to other languages

Side note 2: Specifically for JavaScript, why are these constants not already attached to the global objects browser/globals?

  • 3
  • 3
    What's wrong with using Javascript Date objects? – Erik Eidt Jan 24 '17 at 18:23
  • 1
    Be careful with using constants for time like this. Not every minute has 60 seconds. – zzzzBov Jan 24 '17 at 19:22
  • 1
    C# for example has a TimeSpan which encapsulates the unit and the value. For JavaScript, perhaps checkout the moment.js library, which is useful for managing time. – Matthew Jan 24 '17 at 20:21
  • @ErikEidt I'm using this for things like setTimeout(someFunction, 10 * SECOND), so Date objects won't work for that. Same answer applies to using moment, @Matthew, which I am using for other functionality, but it does not have constants – Merlin -they-them- Jan 24 '17 at 21:10
  • @Merlin-they-them- moment.duration({ seconds: 10 }).asMilliseconds() – Caleth Sep 22 '23 at 13:45
  • Zzzbov. Every minute until 2035 will have 60 seconds. And it seems likely that every minute in anyone’s life time from now on will have 60 seconds. – gnasher729 Sep 22 '23 at 23:25
  • @gnasher729 I see that there are plans to stop doing leap seconds by 2035, but what about the decade+ before then? Leap seconds are only announced six months in advance, so it seems premature to declare that there won't be any more before 2035. Do you have evidence to justify that claim? Also note that even if future leap seconds are eliminated by 2035, there are still the historical leap seconds to deal with. – 8bittree Sep 25 '23 at 15:24

1 Answers1

1

I don't handle constants like that if I can avoid it.

Using the specific example of time in JS, I would use a library that handles those unit conversions itself. Instead of setTimeout(someFunction, 10 * SECOND), I would use something akin to setTimeout(someFunction, moment.duration({ seconds: 10 }).asMilliseconds())

Caleth
  • 10,917