Created
October 10, 2012 23:38
-
-
Save csexton/3869235 to your computer and use it in GitHub Desktop.
jquery-localtime sinatra example
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
require 'sinatra' | |
require 'sinatra/ratpack' | |
require 'coffee-script' | |
helpers do | |
def localtime_tag(time) | |
time = Time.parse(time) unless time.respond_to? :strftime | |
formatted_str = time.strftime('%Y-%m-%dT%H:%M:%S%z') | |
content_tag :span, formatted_str, class: 'localtime' | |
end | |
end | |
get '/' do | |
erb :index | |
end | |
get '/localtime.js' do | |
coffee :localtime | |
end |
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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<title>Sinatra - Localtime</title> | |
</head> | |
<body> | |
<h1>What time is it here?</h1> | |
<ul> | |
<li> "2012-10-10 06:42:47 UTC" => <%= localtime_tag "2012-10-10 06:42:47 UTC" %> | |
<li><%= localtime_tag "2012-10-10 06:42:47 UTC" %> | |
<li><%= localtime_tag Time.now %> | |
<li><%= localtime_tag Time.now.utc %> | |
</ul> | |
<!-- Include JS --> | |
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script> | |
<script src="/localtime.js" type="text/javascript"></script> | |
<script type="text/javascript"> | |
$(document).ready(function() { | |
return $(".localtime").localtime_from_utc(); | |
}); | |
</script> | |
</body> | |
</html> |
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
# | |
# To parse the date the input text should include the zimezone so when the | |
# browser parses the string it will be converted to the local time | |
# | |
# In ruby we can use the following: | |
# date.strftime('%Y-%m-%dT%H:%M:%S%z') | |
# | |
(($) -> | |
$.fn.localtime_from_utc = -> | |
@each -> | |
# get provided date | |
tagText = $(this).html() | |
d = new Date(tagText) | |
# format the date | |
hour = d.getHours() | |
if hour < 12 | |
meridiem = "AM" | |
else | |
meridiem = "PM" | |
hour = 12 if hour is 0 | |
hour = hour - 12 if hour > 12 | |
local_date_string = hour + | |
":" + | |
d.getMinutes() + | |
" " + | |
meridiem + | |
" " + | |
(d.getMonth()+1)+ # Months are zero index | |
"/" + | |
d.getDate() + | |
"/" + | |
d.getFullYear() | |
$(this).html local_date_string | |
$(this).attr "title", tagText | |
) jQuery | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment