Module: Aspera::Units::Timestamp

Defined in:
lib/aspera/units/timestamp.rb

Overview

Point in time given by the user: an absolute date, or a keyword (now, today...) optionally followed by - or + and a Duration, as the date math of Elasticsearch and Grafana, e.g. now-24h, today+9h.

Constant Summary collapse

KEYWORDS =

Keywords, with their description: the reference time, or a midnight

{
  'now'       => 'Current time, e.g. now-24h',
  'today'     => 'Today at midnight, e.g. today+9h',
  'yesterday' => 'Yesterday at midnight',
  'tomorrow'  => 'Tomorrow at midnight'
}.freeze
SYNTAX =

Accepted syntax, for messages

"a date (e.g. 2026-11-27 10:00:00, ISO 8601), or #{KEYWORDS.keys.join(', ')} optionally followed by -<duration> or +<duration> (e.g. now-24h)".freeze

Class Method Summary collapse

Class Method Details

.parse(value, now: Time.now, utc: false) ⇒ Time

Parameters:

  • value (String) —

    Absolute date (a format of Time.parse, e.g. ISO 8601), or now, today, yesterday, tomorrow optionally followed by - (in the past) or + (in the future) and a Duration

  • now (Time) (defaults to: Time.now) —

    Reference time of keywords

  • utc (Boolean) (defaults to: false) —

    true: an absolute date without time zone, and midnight of keywords, are in UTC; else in local time

Returns:

  • (Time)

Raises:



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/aspera/units/timestamp.rb', line 40

def parse(value, now: Time.now, utc: false)
  Aspera.assert_type(value, String) { 'date' }
  text = value.strip
  now = now.getutc if utc
  if (m = text.match(REGEX_KEYWORD))
    base = keyword_time(m[1], now, utc)
    return base if m[2].nil?
    offset = Duration.new(m[3]).microseconds.quo(1_000_000)
    return m[2].eql?('-') ? base - offset : base + offset
  end
  # `Time.parse` reads a duration such as `30s` or `30` as a day of month, `30.5` or `1h30m` or `-1h` as a time of day
  raise ParameterError, "Invalid date: #{value}: for a duration from now, use now#{text}" if text.match?(/\A[-+]/)
  raise ParameterError, "Invalid date: #{value}: for a duration from now, use now-#{text} or now+#{text}" if duration?(text)
  text = "#{text} UTC" if utc && Date._parse(text)[:offset].nil?
  Time.parse(text, now)
rescue ArgumentError => e
  raise ParameterError, "Invalid date: #{value} (#{e.message}): expected #{SYNTAX}"
end