Skip to content

Instantly share code, notes, and snippets.

@chrisroos
Last active July 24, 2024 12:36
Show Gist options
  • Save chrisroos/152c5d0e847e53c1a4bb26c6b3f76b35 to your computer and use it in GitHub Desktop.
Save chrisroos/152c5d0e847e53c1a4bb26c6b3f76b35 to your computer and use it in GitHub Desktop.
Playing with date formatting in liquid templates - Useful in Harmonia task titles
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'liquid'
end
require 'date'
require 'liquid'
GFR_INCORPORATION_DATE = Date.parse('2009-01-12').strftime('%s')
SECONDS_IN_A_WEEK = 7 * 24 * 60 * 60
SECONDS_IN_A_MONTH = 28 * 24 * 60 * 60
def render_template(template, input)
liquid_template = Liquid::Template.parse(template)
liquid_template.render(input)
end
def display_template(title, template)
input = {'due' => Date.today}
puts <<-EndOutput
## #{title}
```
#{template}
```
* Input: #{input}
* Output: #{render_template(template, input)}
---
EndOutput
end
template = <<-EndTemplate
{{ due |
date: '%s' |
minus: #{GFR_INCORPORATION_DATE} |
divided_by: #{SECONDS_IN_A_WEEK}
}}
EndTemplate
display_template('Current GFR week', template)
template = <<-EndTemplate
{{ due |
date: '%s' |
minus: #{GFR_INCORPORATION_DATE} |
minus: #{SECONDS_IN_A_WEEK} |
divided_by: #{SECONDS_IN_A_WEEK}
}}
EndTemplate
display_template('Previous GFR week', template)
template = <<-EndTemplate
{{ due |
date: "%b %Y"
}}
EndTemplate
display_template('Current month', template)
template = <<-EndTemplate
{{ due |
date: "%s" |
minus: #{SECONDS_IN_A_MONTH} |
date: "%b %Y"
}}
EndTemplate
display_template('Last month', template)
template = <<-EndTemplate
{{ due |
date: "%F"
}}
EndTemplate
display_template('Current date', template)

Current GFR week

{{ due |
   date: '%s' |
   minus: 1231718400 |
   divided_by: 604800
}}

  • Input: {"due"=>#<Date: 2017-05-02 ((2457876j,0s,0n),+0s,2299161j)>}
  • Output: 433

Previous GFR week

{{ due |
   date: '%s' |
   minus: 1231718400 |
   minus: 604800 |
   divided_by: 604800
}}

  • Input: {"due"=>#<Date: 2017-05-02 ((2457876j,0s,0n),+0s,2299161j)>}
  • Output: 432

Current month

{{ due |
   date: "%b %Y"
}}

  • Input: {"due"=>#<Date: 2017-05-02 ((2457876j,0s,0n),+0s,2299161j)>}
  • Output: May 2017

Last month

{{ due |
   date: "%s" |
   minus: 2419200 |
   date: "%b %Y"
}}

  • Input: {"due"=>#<Date: 2017-05-02 ((2457876j,0s,0n),+0s,2299161j)>}
  • Output: Apr 2017

Current date

{{ due |
   date: "%F"
}}

  • Input: {"due"=>#<Date: 2017-05-02 ((2457876j,0s,0n),+0s,2299161j)>}
  • Output: 2017-05-02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment