Debian Codegraph @

lib/tomlrb/local_date_time.rb

raw
1 # frozen-string-literal: true
2
3 require 'forwardable'
4
5 module Tomlrb
6 class LocalDateTime
7 extend Forwardable
8
9 def_delegators :@time, :year, :month, :day, :hour, :min, :sec, :usec, :nsec
10
11 def initialize(year, month, day, hour, min, sec) # rubocop:disable Metrics/ParameterLists
12 @time = Time.utc(year, month, day, hour, min, sec)
13 raise ArgumentError, "Invalid Local Date-Time: #{year}-#{month}-#{day}T#{hour}:#{min}:#{sec}" unless min.to_i == @time.min && hour.to_i == @time.hour && day.to_i == @time.day && month.to_i == @time.month && year.to_i == @time.year
14
15 @sec = sec
16 end
17
18 # @param offset [String, Symbol, Numeric, nil] time zone offset.
19 # * when +String+, must be '+HH:MM' format, '-HH:MM' format, 'UTC', 'A'..'I' or 'K'..'Z'. Arguments excluding '+-HH:MM' are supporeted at Ruby >= 2.7.0
20 # * when +Symbol+, must be +:dst+(for summar time for local) or +:std+(for standard time).
21 # * when +Numeric+, it is time zone offset in second.
22 # * when +nil+, local time zone offset is used.
23 # @return [Time]
24 def to_time(offset = '-00:00')
25 return @time if offset == '-00:00'
26 Time.new(year, month, day, hour, min, @sec, offset)
27 end
28
29 def to_s
30 frac = (@sec - sec)
31 frac_str = frac.zero? ? '' : frac.to_s[1..-1]
32 @time.strftime('%FT%T') << frac_str
33 end
34
35 def ==(other)
36 other.is_a?(self.class) &&
37 to_time == other.to_time
38 end
39
40 def inspect
41 "#<#{self.class}: #{self}>"
42 end
43 end
44 end