-
-
Save labocho/ed937483544740a8c2e1 to your computer and use it in GitHub Desktop.
Script parses and prints date time as several formats
This file contains hidden or 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/env ruby | |
| # | |
| # d - Parse and print date time as several formats | |
| # | |
| # Usage: | |
| # | |
| # $ d [DATETIME] | |
| # | |
| # Supported formats: | |
| # | |
| # - Seconds or milliseconds from 1970-01-01T00:00:00Z as decimal integer. | |
| # - ISO8601 / RFC2822 / JIS X 0301 date time format. | |
| # - If argument is ommited, use current time. | |
| # | |
| # Output formats: | |
| # | |
| # - ISO8601 (local) | |
| # - ISO8601 (UTC) | |
| # - RFC2822 (local) | |
| # - RFC2822 (UTC) | |
| # - JIS X 0301 (local) | |
| # - Seconds from 1970-01-01T00:00:00Z | |
| # - Milliseconds from 1970-01-01T00:00:00Z | |
| # | |
| # Example: | |
| # | |
| # $ d 1450159583 | |
| # 2015-12-15T15:06:23+09:00 | |
| # 2015-12-15T06:06:23Z | |
| # Tue, 15 Dec 2015 15:06:23 +0900 | |
| # Tue, 15 Dec 2015 06:06:23 -0000 | |
| # H27.12.15T15:06:23+09:00 | |
| # 1450159583 | |
| # 1450159583123 | |
| # | |
| # $ d 2015-12-15T15:06:23+09:00 | |
| # (same as above) | |
| require "time" | |
| SECONDS_AT_2000 = 946684800 # Seconds from 1970-01-01T00:00:00Z to 2000-01-01T00:00:00Z | |
| def parse(s) | |
| s = s.to_s.dup | |
| s.strip! | |
| if s =~ /\A\d+\z/ # Integer | |
| i = s.to_i | |
| case | |
| when i > SECONDS_AT_2000 * 1_000 | |
| return Time.at(i.to_f / 1_000) | |
| when i > SECONDS_AT_2000 | |
| return Time.at(i) | |
| end | |
| end | |
| if s =~ /\A\d+\.\d+\z/ | |
| f = s.to_f | |
| return Time.at(f) | |
| end | |
| begin | |
| return Time.parse(s) | |
| rescue ArgumentError | |
| end | |
| raise "Cannot parse #{s.inspect}" | |
| end | |
| def print(t) | |
| puts t.getlocal.iso8601 | |
| puts t.utc.iso8601 | |
| puts t.getlocal.rfc2822 | |
| puts t.utc.rfc2822 | |
| puts t.getlocal.to_datetime.jisx0301 | |
| puts t.to_i | |
| puts (t.to_f * 1_000).to_i | |
| end | |
| time = parse(ARGV.first || Time.now.to_f) | |
| print(time) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment