time.util.ts 838 B

1234567891011121314151617181920212223242526272829303132333435
  1. // Utility helpers for time-related operations
  2. const MS_THRESHOLD = 1_000_000_000_000;
  3. /**
  4. * Strictly for persisted timestamps:
  5. * return epoch seconds as bigint (floor)
  6. */
  7. export function nowSecBigInt(): bigint {
  8. return BigInt(Math.floor(Date.now() / 1000));
  9. }
  10. /**
  11. * Convert a runtime value into epoch seconds (bigint).
  12. * Numbers > 1e12 are treated as milliseconds and converted down.
  13. */
  14. export function toSecBigInt(value: number | bigint): bigint {
  15. if (typeof value === 'bigint') {
  16. return value;
  17. }
  18. if (!Number.isFinite(value)) {
  19. return BigInt(0);
  20. }
  21. if (Math.abs(value) > MS_THRESHOLD) {
  22. return BigInt(Math.floor(value / 1000));
  23. }
  24. return BigInt(Math.floor(value));
  25. }
  26. export function nowEpochMsBigInt(): bigint {
  27. return BigInt(Date.now());
  28. }
  29. export function nowMs(): number {
  30. return Date.now();
  31. }