Last active
November 1, 2019 19:33
-
-
Save tsprlng/2600db3ca94c92dadae7ffe7cf6758d1 to your computer and use it in GitHub Desktop.
Date converter utility for things that want shitty Unix timestamps
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/ruby | |
# This program converts dates (from a semi-memorable, short format similar to the standard `date` utility). | |
# It will output them as unix timestamps (it will also accept ISO dates for this conversion). | |
# Or, it can output them in ISO8601, but this will always be in UTC because timezones are pointless. | |
require 'date' | |
class Usage < StandardError | |
end | |
Debug = false | |
Full = ARGV.delete('-d') or ARGV.delete('--date') | |
def date | |
y=mo=d=h=mi=s=nil | |
raise Usage unless ARGV.length == 1 | |
i = ARGV[0] | |
more, s = i.split ?. | |
if more.match /\A[\d-]+T[\d:]+(Z|\+.*)\Z/ | |
return more # Already an ISO date | |
end | |
raise Usage unless more.length % 2 == 0 | |
now = DateTime.now.new_offset(0) | |
more = more.scan /../ | |
case more.length | |
when 1 | |
h, = more | |
when 2 | |
h, mi = more | |
when 3 | |
d, h, mi = more | |
when 4 | |
mo, d, h, mi = more | |
when 5 | |
mo, d, h, mi, _y = more | |
y = now.year - (now.year % 100) + _y.to_i | |
when 6 | |
mo, d, h, mi, _c, _y = more | |
y = _c.to_i * 100 + _y.to_i | |
else | |
raise Usage | |
end | |
Debug and p y, mo, d, h, mi, s | |
y ||= now.year | |
mo ||= now.month | |
d ||= now.day | |
mi ||= '00' | |
s ||= '00' | |
Debug and puts | |
Debug and p y, mo, d, h, mi, s | |
return "#{y}-#{mo}-#{d}T#{h}:#{mi}:#{s}Z" | |
rescue Usage | |
$stderr.puts "Usage: #{$0} [-d|--date] [[MM]DD]hhmm[[CC]YY][.ss]" | |
$stderr.puts | |
$stderr.puts " --date: Print UTC (Z) ISO date string instead of timestamp" | |
exit 1 | |
end | |
if Full | |
puts DateTime.parse(date).new_offset(0).iso8601.sub('+00:00','Z') | |
else | |
puts DateTime.parse(date).to_time.to_i | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment