Git Product home page Git Product logo

local_time's Introduction

Local Time

Local Time makes it easy to display times and dates to users in their local time. Its Rails helpers render <time> elements in UTC (making them cache friendly), and its JavaScript component immediately converts those elements from UTC to the browser's local time.

Installation

Importmaps

  1. Add gem "local_time" to your Gemfile.

  2. Run bundle install

  3. Run bin/importmap pin local-time to add the local-time npm package

  4. Add this to app/javascript/application.js

    import LocalTime from "local-time"
    LocalTime.start()

Webpacker

  1. Add gem "local_time" to your Gemfile.

  2. Run bundle install

  3. Run yarn add local-time

  4. Add this to app/javascript/packs/application.js

    import LocalTime from "local-time"
    LocalTime.start()

Example

> comment.created_at
"Wed, 27 Nov 2013 18:43:22 EST -0500"
<%= local_time(comment.created_at) %>

Renders:

<time data-format="%B %e, %Y %l:%M%P"
      data-local="time"
      datetime="2013-11-27T23:43:22Z">November 27, 2013 11:43pm</time>

And is converted client-side to:

<time data-format="%B %e, %Y %l:%M%P"
      data-local="time"
      datetime="2013-11-27T23:43:22Z"
      title="November 27, 2013 6:43pm EDT"
      data-localized="true">November 27, 2013 6:43pm</time>

(Line breaks added for readability)

Time and date helpers

<%= local_time(time) %>

Format with a strftime string (default format shown here)

<%= local_time(time, '%B %e, %Y %l:%M%P') %>

Alias for local_time with a month-formatted default

<%= local_date(time, '%B %e, %Y') %>

To set attributes on the time tag, pass a hash as the second argument with a :format key and your attributes.

<%= local_time(time, format: '%B %e, %Y %l:%M%P', class: 'my-time') %>

To use a strftime format already defined in your app, pass a symbol as the format.

<%= local_time(date, :long) %>

When using the local_time helper I18n.t("time.formats.#{format}"), I18n.t("date.formats.#{format}"), Time::DATE_FORMATS[format], and Date::DATE_FORMATS[format] will be scanned (in that order) for your format.

When using the local_date helper, I18n.t("date.formats.#{format}"), I18n.t("time.formats.#{format}"), Date::DATE_FORMATS[format], and Time::DATE_FORMATS[format] will be scanned (in that order) for your format.

Note: The included strftime JavaScript implementation is not 100% complete. It supports the following directives: %a %A %b %B %c %d %e %H %I %l %m %M %p %P %S %w %y %Y %Z

Time ago helpers

<%= local_time_ago(time) %>

Displays the relative amount of time passed. With age, the descriptions transition from {quantity of seconds, minutes, or hours} to {date + time} to {date}. The <time> elements are updated every 60 seconds.

Examples (in quotes):

  • Recent: "a second ago", "32 seconds ago", "an hour ago", "14 hours ago"
  • Yesterday: "yesterday at 5:22pm"
  • This week: "Tuesday at 12:48am"
  • This year: "on Nov 17"
  • Last year: "on Jan 31, 2012"

Relative time helpers

Preset time and date formats that vary with age. The available types are date, time-ago, time-or-date, and weekday. Like the local_time helper, :type can be passed a string or in an options hash.

<%= local_relative_time(time, 'weekday') %>
<%= local_relative_time(time, type: 'time-or-date') %>

Available :type options

  • date Includes the year unless it's current. "Apr 11" or "Apr 11, 2013"
  • time-ago See above. local_time_ago calls local_relative_time with this :type option.
  • time-or-date Displays the time if it occurs today or the date if not. "3:26pm" or "Apr 11"
  • weekday Displays "Today", "Yesterday", or the weekday (e.g. Wednesday) if the time is within a week of today.
  • weekday-or-date Displays the weekday if it occurs within a week or the date if not. "Yesterday" or "Apr 11"

Configuration

Internationalization (I18n)

Local Time includes a set of default en translations which can be updated directly. Or, you can provide an entirely new set in a different locale:

LocalTime.config.i18n["es"] = {
  date: {
    dayNames: [  ],
    monthNames: [  ],},
  time: {},
  datetime: {}
}

LocalTime.config.locale = "es"

Note

The "default" keys in the i18n configuration object are used for translations in LocalTime's RelativeTime module. They are not used to determine which format is rendered when none is provided. See #128 for details.

24-hour time formatting Local Time supports 24-hour time formats out of the box.

To use this feature, configure the library to favor data-format24 over data-format attributes:

LocalTime.config.useFormat24 = true

The library will now default to using the data-format24 attribute on <time> elements for formatting. But it will still fall back to data-format if data-format24 is not provided.

The included Rails helpers will automatically look for 24h variants of named formats. They will search for #{name}_24h in the same places the regular name is looked up.

This is an example of what your app configuration might look like:

Time::DATE_FORMATS[:simple] = "%-l:%M%P"
Time::DATE_FORMATS[:simple_24h] = "%H:%M"

When :type is set to time-ago, the format is obtained from the I18n configuration.

In practice, you might set config.useFormat24 to true or false depending on the current user's configuration, before rendering any <time> elements.

Contributing

Please read CONTRIBUTING.md.

local_time's People

Contributors

a-nickol avatar bryant1410 avatar choonkeat avatar cschulte22 avatar dependabot[bot] avatar e2 avatar javan avatar josefarias avatar knack avatar pdobb avatar rajiv avatar rossta avatar seanpdoyle avatar twalpole avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

local_time's Issues

No support for prefixing with minus to eliminate leading zeros

Using the - format for newer versions of strftime doesn't output correctly. Since there is a dependency on the system's strftime version, it seems like it could support both (and just always fall back to %m and %d. Obviously using %e instead of %-d is an option for day, but there isn't a great alternative for month.

Consider this example:

"Ends #{ local_time(auction.ends_at, '%m/%d at %l:%M%P %Z') }".html_safe

yields the correct date:

Ends 09/24 at 2:13pm CDT

Meanwhile,

"Ends #{ local_time(auction.ends_at, '%-m/%-d at %l:%M%P %Z') }".html_safe

yields this incorrectly:

Ends %-m/%-d at 2:13pm CDT

which should yield:

Ends 9/24 at 2:13pm CDT

How to localize on server side?

I have a non-english Rails app which use local_time gem:

<%= local_time_ago(obj.created_at) %>

I am trying to localize it. On the client side, everything is working just fine. The text shows in my custom language. But on the first load of the page I get the english text (I guess this is the server side text?). How to set the locale of local_time gem on server side? I have already set config.i18n.default_locale

I dont want it to wrap date with <time> tag

I have been using local_time to convert servertime to client local time. However now I am using datatables and to sort date/time columns. I have to use date-moment.js plugin of Datatables which uses moment.js to handle date conversions.

My problem is: the local_time's view helper is wrapping the date with < time > tag like this

<time data-format="%B %e, %Y %l:%M%P"
      data-local="time"
      datetime="2013-11-27T23:43:22Z"
      title="November 27, 2013 6:43pm EDT"
      data-localized="true">November 27, 2013 6:43pm</time>

The wrapping thing is creating problem for moment.js to get the actual date-time as it expects. I need it to convert the date-time but not wrap with <time> tag. Is it possible. If yes How?

'argument out of range'

Hi I just stumbled upon local_time and I am wanting to use it for a playlist, some 100 timestamps spread out over a whole day. Presenting the playlist to our listeners in their local timezone ...

However I am supplying a strange timestamp that I am getting from my JSON api.
0312201217:52:09 %d%m%Y%H:%M:%S

When I supply following timestamp local_time(time, format: '%d%m%Y%H:%M:%S' )

I get an error 'argument out of range'. I could not find this error message anywhere in your code, maybe you have hint how to fix this.

BTW if my timestamps already come from a certain timezone, could I supply a timezone other than UTC?

Thanks alot for the engine!

not displaying timezone on windows

When using local_time in a windows browser it does not display the timezone.

local_time(datetime,'%l:%M %p (%Z)')

When doing this to display the time %Z returns nothing on windows.

On unix it correctly shows code.

I believe this is because on unix it formats the time as : Tue Jun 24 2014 13:19:42 GMT-0600 (EDT)

However on windows it is : Tue Jun 24 2014 13:19:42 GMT-0400 (Eastern Daylight Time)

This piece seems to be broken:
`parseTimeZone = (time) ->
string = time.toString()

Sun Aug 30 2015 10:22:57 GMT-0400 (NAME)

if name = string.match(/(([\w\s]+))$/)?[1]
if /\s/.test(name)
# Sun Aug 30 2015 10:22:57 GMT-0400 (Eastern Daylight Time)
name.match(/\b(\w)/g).join("")
else
# Sun Aug 30 2015 10:22:57 GMT-0400 (EDT)
name`

undefined local variable or method `time'

Hi,

Environment:

Ruby 2.4.3 and Rails 5.1.4
Ubuntu 14.04

I added <%= local_time(time) %> at app/views/layouts/application.html.erb and getting below error


undefined local variable or method `time' for #<#<Class:0x00007f10b14940d0>:0x00007f10b14763f0>
Did you mean?  timer

How to fix it ?

Thanks.

'%-d' not supported

This is more of a feature request than a bug, but %-d isn't supported, while %d is.

Recreate with the following:

LocalTime.strftime(new Date, '%a %b %d %l:%M %p %Z')
LocalTime.strftime(new Date, '%a %b %-d %l:%M %p %Z')

Output:

"Tue Sep 01 12:38 PM CDT"
"Tue Sep %-d 12:38 PM CDT"

Expected Output

"Tue Sep 01 12:38 PM CDT"
"Tue Sep 1 12:38 PM CDT"

From the ruby DateTime doc:

    %d - Day of the month, zero-padded (01..31)
            %-d  no-padded (1..31)

If I can find where this is happening when I'm free, I'll take a stab at it myself.

Use in mailer

How to use either local_time or local_relative_time helper in emails?

JS support for non-padded values (%-d)

If I have a DateTime object (datetime = DateTime.parse('5/8/10 8:53')), and strftime it with non-padded indicators (like %-e and %-I), in ruby-land, it all renders correctly

Time.now.utc.strftime('%b %-e, %Y %-l:%M %p') # => "Aug 5, 2010 8:53 AM"

and it works great with local_time

local_time(Time.now.utc, Time.now.utc) 
#=> <time datetime=\"2010-08-05T08:53:00+00:00\" data-local=\"time\" data-format=\"%b %-e, %Y %-l:%M %p\">Aug 5, 2010 8:53 AM</time>

But the javascript seems to lack compatibility

<time datetime="2010-8-5T08:53:00Z" data-local="time" data-format="%b %-e, %Y %-l:%M %p" title="August 8, 2010 at 8:53am EST" data-localized="true">Aug %-e, 2010 %-l:53 AM</time>

It ultimately renders Aug %-e, 2010 %-l:53 AM, which is not expected.

Doesn't work with Firefox

The use of element.innerText = means this doesnt work with FF - I believe element.textContent = should work

Some kind of cache

Hi,
I'm using local time like this:
<td><%= local_time(node.last_seen) %></td>
And when I'm opening the page I see non-converted time:
<time datetime="2017-03-30T17:36:39Z" data-local="time" data-format="%B %e, %Y %l:%M%P">March 30, 2017 5:36pm</time>
After I'm pressing F5 to refresh the page:
<time datetime="2017-03-30T17:36:39Z" data-local="time" data-format="%B %e, %Y %l:%M%P" title="March 30, 2017 at 8:36pm RST" data-localized="true">March 30, 2017 8:36pm</time>

So, it's smells like some kind of caching. Maybe I'm cooking gem in wrong way?

Thank you.

Get last user's Time Zone and store it in database ...

For my purpose is important that administrator of the app will see last user's timezone ... Is it possible to get user's timezone somehow into controller and store in users profile ... ?
Very essencital for me ... O:)
THX!!

LocalTime fails to initialize when loaded via <script async>

When LocalTime is loaded via an async script tag, like this:

<script src="/assets/application-######.js" async></script>

Then there is a possibility that the browser will load the document and fire the DOMContentLoaded event before parsing and executing the LocalTime JavaScript. This is 100% reproducible in my current project using Firefox 46.0.1 and Safari Technical Preview v5.

LocalTime depends on receiving the DOMContentLoaded event in order to initialize. Without it, its domLoaded variable is permanently set to false, which essentially disables the entire library.

This is a common problem and is well documented (and answered) in this Stack Overflow question: http://stackoverflow.com/questions/9237044/async-loaded-scripts-with-domcontentloaded-or-load-event-handlers-not-being-call .

The solution, it seems, is to check if (document.readyState !== "loading") at parse time. If this evaluates to true, then LocalTime should initialize immediately instead of waiting for a DOMContentLoaded event that will never arrive.

I can open a PR to make this change, but since JavaScript is not my strong suit, I thought I would get feedback via a bug report first. Is this a reasonable fix?

As it stands, the workaround in my particular project will be to remove async from my script tag.

time zone is incorrect when loading but changes sometime later

The time in my app is incorrect when reloading the page, but changes to the correct time at some point later (usually within a split second, but sometimes it takes a few). I've followed everything in the docs to the tee, and I have LocalTime.run(); in my Action Cable function as suggested in this answer.

How can I make this work so that the seams are not showing?

Incorrect format because of the scan order

I18n.t("time.formats.#{format}"), I18n.t("date.formats.#{format}"), Time::DATE_FORMATS[format], and Date::DATE_FORMATS[format] will be scanned (in that order) for your format.

According to this behavior a Date object will be formatted with time formats.

en:
  time:
    formats:
      default: '%H'
  date:
    formats:
      default: '%a'
<%= local_date(Date.today, format: :default) %> # will be formatted as time

timer with hour:min:sec

Hi,

Is there a timer functionality available ?

I could not find the timer command.

Let me know how to implement it.

Thanks.

how to display "an hour 2 min ago"

With <%= local_time_ago(time) %>, I could see "an hour ago", but I would like to see "an hour 2 min ago".

How should I achieve it ?

Thanks.

local_time_ago() switching to absolute time

In my view I have the line:

<%= local_time_ago(note.updated_at) %>

This correctly displays something like "22 minutes ago"

However, if I then click a link

<%= link_to "Home", root_path %>

that reloads the same page it suddenly changes to something like "December 12, 2013 6:58am"

If I wait a minute it updates and switches back to the nice form like "24 minutes ago"

Any way to prevent this intermediate state? Am I doing something wrong.

This is using 0.2.0 version of the gem. It happens both with the latest Chrome Version 31.0.1650.63 and latest Safari Version 7.0 (9537.71)

`weekday` is not cache friendly

if cached page is more than a week old, <time> will remain blank even after LocalTime.run()

So either we introduce weekday-or-date (or fix weekday to behave like that)

when "weekday-or-date"
  relativeWeekday(time) ? relativeDate(time)

Time isn't replaced when firing time:elapse

Calling $(document).trigger('time:elapse'); doesn't seem to replace times added via ajax.

I'm building a blog where I want readers to be able to add comments via ajax, but when I create a comment, the utc time of the comment is shown and isn't replaced by the relative time.

My comments/create.js.erb view looks like this:

var $comment = $("<%= j render(@comment) %>");

$('#new_comment').slideUp(function () {
  $comment.replaceAll(this).hide().slideDown();
  $(document).trigger('time:elapse');
});

Time zone incorrect

Hello,

For some reason, local_time is showing time stamps in the future by 4 hours. My application.rb does not change the default time zone from UTC, however there is a before_action that sets the Time.zone to the current user's time zone, which in my case is "Eastern Time (US & Canada)".

Anywhere I render a date without using local_time, the time zone conversion is accurate, however when I substitute with local_time, I'm jumped ahead by 4 hours. Can you help point me in the right direction?

UTC times seem to stay in UTC time

In my application, no user time zone is set. All times are in UTC.

record.created_at renders as
"2015-01-08 18:25:41 UTC"

and when used with <%= local_time(record.created_at) %>

it renders as
January 8, 2015 6:09pm

which ultimately displays as "6:009PM" even though it is "10:09AM" where I am (PST)

It seems the time is just staying in UTC.

I had hoped that UTC would display in the zone of the browser automatically. Perhaps that is a configuration option.

Changing actual time

This is my code:
<%= local_time(conversation.updated_at, '%l:%m %p') %>

This produces:
<time datetime="2017-05-22T23:00:35Z" data-local="time" data-format="%l:%m %p" title="May 22, 2017 at 4:00pm PDT" data-localized="true">4:05 PM</time>

Why does it say "4:05" in the actual text that displays, in spite of the fact that both the time stamp and even the title both clearly end in ":00"?

This is bizarre, and I haven't the foggiest idea where to even look... it's doing this with many different times, too (:24, :23, :39, etc.). It's not the javascript doing it... when I look at what comes back from my server, the "HTML time" ends in :05, as well:
<time datetime="2017-05-22T23:00:35Z" data-local="time" data-format="%l:%m %p">11:05 PM</time>

Anyone have any help for me?

Add i18n support

Are there any plans to add i18n support @javan?
We would love to use this plugin but our side serves english and german content.
It look like the only similar plugin with i18n support is http://timeago.yarp.com/.

undefined method `local_time' error

I have installed gem 'local_time' in my application and require 'local_time' in application.js properly.
But, when i try to use local_time helper. Its showing error that local_time is not defined.

= local_time(User.first.created_at)
=>
undefined method `local_time' for #<#<Class:......>

i18n month not beign translated

Using local_time(datetime, :long) doesnt translates correctly the month (shows on default en language), long format is defined as '%d de %B de %Y' as is on language es-ES. (Using l(datetime) shows the date correctly translated, but not in local time as aims this gem).

Publish javascript to npm?

I'm in the process of converting a large Rails project over to Webpacker and we have local_time as a dependency. Hence, it'd be great to make the javascript inthis project available via NPM. Looks like this would require a release step to build JS from the CoffeeScript source, make compatible with requireJS/ES6-modules, and coordinate publishing to Rubygems and NPM, or perhaps having a separate repo altogether.

Is this something you'd consider for this project?

RelativeTimeAgo only works in english

Hi, have you thought a way to translate in javascript? I could just re-write your class code in another language but that is not cool....

Maybe in the helper tag add the translations as a hash with fallback as the current ones? There are not too many translations in that Class anyway:

"#{ago} ago"
"#{day} at #{@formatTime()}"
"on #{@formatDate()}"
"a second"
"#{sec} seconds"
"a minute"
"#{min} minutes"
"an hour"
"#{hr} hours"
"today"
"yesterday"

Timezone abbreviations not always correct.

When using %Z format specifier, some abbreviations are not the same as in abbreviation tables such as: https://www.timeanddate.com/time/zones/.

For instance, Alaska Daylight Time should be abbreviated as AKDT and instead is showing as ADT which is Atlantic Daylight time.

Gem version used: 2.0.1

Steps to reproduce:

  1. Include <%= local_time(Time.now, format: "%I:%M %p %Z") %> in a test view.
  2. Force a geolocation using the browser's dev tools. Use Location name: Anchorage, Lat: 61.2181, Long: -149.9003, Timezone ID: America/Anchorage (In Chrome this is done by opening Dev tools and selecting (settings)>>more tools >> sensors, and then click on add location)

local_time does not display proper time when put inside bootstrap's tooltip

I'm having a problem displaying the correct time when I put local_time inside of Bootstrap's tooltip. Formatting works, but the time remains UTC time instead of PDT time.

<% @product.users.each do |user| %>
  <% if user.active %>
    <img src="<%= user.image %>" class="user-image" data-toggle="tooltip" data-placement="bottom" data-html="true" title='Last Logged in: <br> <%= local_time(user.updated_at) %>' />
    <% end %>
 <% end %>

Would display

Last Logged In:
December 18, 2015 3:53am

instead of

Last Logged In:
December 18, 2015 7:53pm

So it does format the date, it just doesn't change the date to my local time zone like I wanted it to.

Javascipt API, localtime

Is it possible to access the localized time in Javascript?

In this example from the docs:
LocalTime.strftime(new Date( "Jun 24 2014 13:19:42" ), "%l:%M%P")

The timezone offset has not been applied, and I don't see how to do so.

ActionView::Template::Error (couldn't find file 'local_time' with type 'application/javascript')

Hey guys, thanks for the great gem.

I just upgraded to Rails 5.0.3 and local_time 2.0 and I get this error:

ActionView::Template::Error (couldn't find file 'local_time' with type 'application/javascript'
Checked in these paths:
....
....
  /Users/Ahmad/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/local_time-2.0.0/app/assets/javascripts

It seems to have installed the gem but can't find it. Reverting back to 1.0.3 the error goes away.

Thanks

handle nil

If a time passed to local_time_ago happens to be nil, it will throw an error:

undefined method `to_time' for nil:NilClass

would it be possible to have local_time_ago handle this gracefully by returning nil or ''?

I18N for local_time_ago.

I want to replace Jquery-time-ago to local_time but the only reason that I didn't is that i can't use I18n for local_time_ago helper.
Thank you.

show time instead of hrs if less than 1 day

hi
any way to modify the time to show "time"(at 12:32 am) instead of "hours" (less than 5 hrs) for less than 1 day
also, to include time if on other day of year or another year?
thnx

The gem is slow in converting

Sometimes the gem takes maybe more than a minute to convert the text using the local_time_ago helper. Anyone aware about this and/or knows a solution? I'm also using turbolinks, if that can be an issue.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.