Dealing with date and time in rails and how does postgres store datetime

Every real-time application needs to deal with Date and Time.In rails, Time, Date and DateTime classes reside inside ruby library, Date and Time inheriting the Object class. DateTime inherits from Date class. Current Time, Date and both can be easily accessible using instance methods of these above class methods.

[45] pry(main)> Date.superclass
=> Object
[46] pry(main)> Time.superclass
=> Object
[47] pry(main)> DateTime.superclass
=> Date

Accessing current date, time and both in rails.

[25] pry(main)> DateTime.now
=> Fri, 06 Oct 2017 18:06:50 +0000
[26] pry(main)> Date.today
=> Fri, 06 Oct 2017
[27] pry(main)> Time.now
=> 2017-10-06 18:07:07 +0000

How does Postgres store DateTime using rails…?

Postgres always stores Datetime data in utc format. When a sql query is made, the datetime format is converted into utc time, if necessary, before sql query is applied to database. For example, we make a sql query with IST timings, the datetime is converted to utc and sql query is applied.

d = DateTime.now.in_time_zone("Asia/Kolkata")
=> Sat, 07 Oct 2017 00:38:26 IST +05:30
[57] pry(main)> d
=> Sat, 07 Oct 2017 00:38:40 IST +05:30
[58] pry(main)> Booking.where('created_at > ?', d).count
   (1.4ms)  SELECT COUNT(*) FROM "bookings" WHERE (created_at > '2017-10-06 19:08:40.011480')
D, [2017-10-06T19:10:37.734437 #1] DEBUG -- :    (1.4ms)  SELECT COUNT(*) FROM "bookings" WHERE (created_at > '2017-10-06 19:08:40.011480')
D, [2017-10-06T19:10:37.734724 #1] DEBUG -- :    (1.4ms)  SELECT COUNT(*) FROM "bookings" WHERE (created_at > '2017-10-06 19:08:40.011480')
=> 3

Observe that we gave a sql query for datetime with IST timezone (07 Oct 2017 00:38:40 IST +05:30), but the query was made using UTC format (2017-10-06 19:08:40.011480) in postgres.

Dealing with TimeZone

Rails would give utc time by default. In order to have IST or EST datetime, configuration at config/application.rb needs to be changed respectively.

config.time_zone = "Asia/Kolkata"
config.time_zone = "Eastern Time (US & Canada)"

Using in_time_zone(timezone) gives DateTime from timezone specified.

DateTime.now.in_time_zone('Asia/Kolkata')
=> Sat, 07 Oct 2017 01:22:11 IST +05:30
DateTime.now.in_time_zone('Eastern Time (US & Canada)')
=> Fri, 06 Oct 2017 15:53:20 EDT -04:00

Strftime

Formats date according to the directives in the given format string. The directives begins with a percent (%) character. Any text not listed as a directive will be passed through to the output string.

Syntax : strftime( format )

DateTime.now
=> 2017-10-06 19:29:38 UTC
t.strftime("%H")  => "19"      # Hour of the time in 24 hour clock format
t.strftime("%I")  => "07"      # Hour of the time in 12 hour clock format
t.strftime("%M")  => "29"      # Minutes of the time
t.strftime("%S")  => "38"      # Seconds of the time
t.strftime("%Y")  => "2017"    # Year of the time
t.strftime("%m")  => "10"      # month of the time
t.strftime("%d")  => "06"      # day of month of the time
t.strftime("%w")  => "5"       # day of week of the time
t.strftime("%a")  => "Fri"     # name of week day in short form of the
t.strftime("%A")  => "Friday"  # week day in full form of the time
t.strftime("%b")  => "Oct"     # month in short form of the time
t.strftime("%B")  => "October" # month in full form of the time
t.strftime("%y")  => "17"      # year without century of the time
t.strftime("%Z")  => "UTC"     # Time Zone of the time
t.strftime("%p")  => "PM"      # AM / PM of the time

2 Responses to “Dealing with date and time in rails and how does postgres store datetime

  • Hello,

    After visiting your website to check its loading speed, we’ve thought you could be interested in our top notch hosting services…

    Due to high competition these days, it is crucial that your website loads as fast as possible for your online success : more sales and better ranking.
    This is impacting directly your revenues and ranking, we have selected a few articles that explain it :
    https://www.yoorshop.fr/announcements/436/Impact-of-loading-speed-of-your-site-on-your-revenues-and-SEO.html

    To get a fast loading website, you need to meet both conditions :
    1 – Primary level in back-end : performant and optimized hosting service with a server located on the continent where you target market (Just moving your website to us will make it load faster, it was the case for 95% of other clients)
    2 – Secondary level in front-end : your website should be optimized as much as possible

    Your website should not exceed 3 sec/page on average, the important loading speed criteria is the ‘Start Render’ on various pages on your website.
    We have built a comprehensive knowledge base so that help users to understand the subtleties and technical aspects of assessing properly : server speed, website optimization, and simulate the reality of user’s experience on your website.
    Please check : https://www.yoorshop.fr/knowledgebase/45/E-Optimization-and-SEO

    Most of our clients came from other web hosts. They came to Us for performance, not for fun, their conclusion has been very clear :
    “in 95% of the cases, all clients told that the loading speed of their website increased as soon as their website started loading from our servers, and even when previous host was pretty fast…”

    Your website can only rock with us thanks to the best servers of the market :
    https://www.yoorshop.fr/knowledgebase/3019/Diagram-100-SSD-3D-V-NAND-server-with-Fastpath.html

    You will benefit of an optimized hosting service delivering extreme performances and best features :
    – No contract commitment
    – Servers located in Europe in 13 countries, and in Canada for US continent
    – Help desk, average response time : 30 min
    – SSL certificate : Free and Unlimited
    – Backups : last 10 days
    – 100% SSD servers
    – Backups : last 10 days
    – Nginx server with LiteSpeed PHP
    – Optimized database server MariaDB
    – Cache enabled by default : Opcache, browser
    – Http2 (use SSL)
    – Pagespeed module (to help optimize your website)
    – Brotli compression
    – Advanced threat and traffic protection, WAF included
    – Free VPN L2TP and/or OPenVPN

    Test our services risk free with :
    30 days Money Back Guarantee’ + Free Website Migration !

    Get 5% discount lifetime on any billing cycle with this voucher code : YUPB0NVK5R

    If you have any questions, please use our contact form on our website :
    https://www.yoorshop.fr/contact.php

    Thank you for your attention,
    Yours faithfully,
    Daniel – Customer service YOORshop
    YOORshop SAS – RCS Lyon 817466147
    52 route du clos, 69700 Montagny – France

    NB : this message is a one time commercial proposal, this a NOT a subscription to any mailing list, you will not be contacted again

  • Предлагаем нашим клиентам чудодейственное средство для снижения веса сироп Мангустина. С его помощью можно сжечь около 15 килограмм за 2 недели.

    Растение гарциния произрастает на Шри-Ланке. Плоды этого дерева имеют удивительные свойства. В баночке содержится около 25 плодов данного замечательного растения. Плоды растения мангустин помогают сжечь излишнею жировую ткань. И положительно воздействуют на организм в целом. Технология производства препарата, а также уникальная упаковка помогают сохранить все удивительные свойства мангустина.

    Главным компонентом сиропа Мангустина являются фрукты с дерева мангостан, в них имеется огромное число полезных веществ. Благодаря компоненту окиси дифениленкетона, которое в больших дозах имеется во фрукте, значительно тормозятся процессы окисления в организме. Окись дифениленкетона считается одним из самых сильных антиоксидантов. В плоде растения гарциния вдобавок есть различные витамины и элементы. Приобрести сироп Mangoosteen возможно на веб-сайте http://mangoo77.mangoosteen.com.

    Официальный сайт: http://mangystin.bxox.info
    Вам будет интересно: http://work.stockbag.info

Leave a Reply

Your email address will not be published. Required fields are marked *