1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 15:18:01 +00:00

Add Format DateTime With Builtin Formats as a Rails TIL

This commit is contained in:
jbranchaud
2025-04-30 23:18:32 -05:00
parent 0d173ccaaf
commit d8dfcce0fc
2 changed files with 51 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
_1641 TILs and counting..._
_1642 TILs and counting..._
See some of the other learning resources I work on:
- [Get Started with Vimium](https://egghead.io/courses/get-started-with-vimium~3t5f7)
@@ -1048,6 +1048,7 @@ If you've learned something here, support my efforts writing daily TILs by
- [Find Or Create A Record With FactoryBot](rails/find-or-create-a-record-with-factory-bot.md)
- [Find Records With Multiple Associated Records](rails/find-records-with-multiple-associated-records.md)
- [Force All Users To Sign Out](rails/force-all-users-to-sign-out.md)
- [Format DateTime With Builtin Formats](rails/format-datetime-with-builtin-formats.md)
- [Generate A Model](rails/generate-a-model.md)
- [Generate A Rails App From The Main Branch](rails/generate-a-rails-app-from-the-main-branch.md)
- [Generating And Executing SQL](rails/generating-and-executing-sql.md)

View File

@@ -0,0 +1,49 @@
# Format DateTime With Builtin Formats
The Rails [`Date`](https://api.rubyonrails.org/classes/Date.html)/`DateTime`
and [`Time`](https://api.rubyonrails.org/classes/Time.html) classes each come
with a `DATE_FORMATS` constant that is a hash of symbol names to format
strings.
```ruby
> DateTime::DATE_FORMATS
=>
{:short=>"%d %b",
:long=>"%B %d, %Y",
:db=>"%Y-%m-%d",
:inspect=>"%Y-%m-%d",
:number=>"%Y%m%d",
:long_ordinal=>
#<Proc:0x0000000105b2cef0 /Users/jbranchaud/.local/share/mise/installs/ruby/3.2.2/lib/ruby/gems/3.2.0/gems/activesupport-8.0.1/lib/active_support/core_ext/date/conversions.rb:15 (lambda)>,
:rfc822=>"%d %b %Y",
:rfc2822=>"%d %b %Y",
:iso8601=>
#<Proc:0x0000000105b2cec8 /Users/jbranchaud/.local/share/mise/installs/ruby/3.2.2/lib/ruby/gems/3.2.0/gems/activesupport-8.0.1/lib/active_support/core_ext/date/conversions.rb:21 (lambda)>}
```
These can be used as a standardized, ready-to-use, named formats when turning
`DateTime` objects into strings.
Here are a few examples
```ruby
> now = DateTime.now
=> Wed, 30 Apr 2025 23:08:08 -0500
> now.to_fs(:long)
=> "April 30, 2025 23:08"
> now.to_fs(:long_ordinal)
=> "April 30th, 2025 23:08"
> now.to_fs(:iso8601)
=> "2025-04-30T23:08:08-05:00"
```
If an unrecognized key is passed to `#to_fs`, then it falls back to the
`:iso8601` format.
```ruby
> now.to_fs(:taco_bell)
=> "2025-04-30T23:08:08-05:00"
```