From d8dfcce0fcc79a78dfbfd8ca21618080a1192159 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Wed, 30 Apr 2025 23:18:32 -0500 Subject: [PATCH] Add Format DateTime With Builtin Formats as a Rails TIL --- README.md | 3 +- rails/format-datetime-with-builtin-formats.md | 49 +++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 rails/format-datetime-with-builtin-formats.md diff --git a/README.md b/README.md index 7731fd0..25f13a2 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/rails/format-datetime-with-builtin-formats.md b/rails/format-datetime-with-builtin-formats.md new file mode 100644 index 0000000..b2940eb --- /dev/null +++ b/rails/format-datetime-with-builtin-formats.md @@ -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=> + #, + :rfc822=>"%d %b %Y", + :rfc2822=>"%d %b %Y", + :iso8601=> + #} +``` + +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" +```