Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: e409045c48
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 80 lines (65 sloc) 1.99 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
require 'rubygems'
require 'sinatra'
require 'chronic'
require 'date'
require 'cgi'

ENV['RACK_ENV'] ||= "development"
ENV['TIMEAPI_MIME'] ||= "text/plain"

module TimeAPI
  
  class App < Sinatra::Base
 
    configure do
      disable :sessions
      set :environment, ENV['RACK_ENV']
    end

    helpers do
      # convert zone to offset
      def z2o(zone)
        offsets = { "PST" => -8, "MST" => -7, "CST" => -6, "EST" => -5,
                    "PDT" => -7, "MDT" => -6, "CDT" => -5, "EDT" => -4,
                    "UTC" => 0, "GMT" => 0 }
        offsets[zone ? zone.upcase : "UTC"]
      end
    end
  
    get '/' do
      erb :index
    end

    post '/' do
      throw :halt, [400, "Bad request, missing 'dt' parameter"] unless params[:dt]
      content_type ENV['TIMEAPI_MIME']
      offset = z2o(params[:zone])
      Time.new.utc.to_datetime.new_offset(Rational(offset, 24)).to_s
    end
    
    get '/favicon.ico' do
      ''
    end
    
    get '/:zone' do
      content_type ENV['TIMEAPI_MIME']
      offset = z2o(params[:zone])
      Time.new.utc.to_datetime.new_offset(Rational(offset,24)).to_s
    end
    
    get '/:zone/:time' do
      offset = z2o(params[:zone])
      result = Chronic.parse(CGI.unescape(params[:time]),:now=>Time.new.utc.to_datetime.new_offset(Rational(offset,24)))
      throw :halt, [400, "Bad request"] unless result
      content_type ENV['TIMEAPI_MIME']
      result.to_datetime.new_offset(Rational(offset,24)).to_s
    end

    # start the server if ruby file executed directly
    run! if app_file == $0
  end
end

class Time
  def to_datetime
    # Convert seconds + microseconds into a fractional number of seconds
    seconds = sec + Rational(usec, 10**6)

    # Convert a UTC offset measured in minutes to one measured in a
    # fraction of a day.
    offset = Rational(utc_offset, 60 * 60 * 24)
    DateTime.new(year, month, day, hour, min, seconds, offset)
  end
end

class DateTime
  def to_datetime
    self
  end
end
Something went wrong with that request. Please try again.