lesli_date 1.1.0 → 1.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +33 -0
- data/Rakefile +3 -3
- data/docs/about/configuration.md +174 -0
- data/docs/about/development.md +131 -0
- data/docs/about/installation.md +48 -0
- data/docs/api/database.md +89 -0
- data/docs/api/examples.md +113 -0
- data/docs/api/formatter.md +104 -0
- data/docs/api/index +6 -0
- data/docs/api/overview.md +26 -0
- data/docs/api/parsing.md +102 -0
- data/docs/images/date-logo.svg +1 -0
- data/docs/navigation +2 -0
- data/lib/lesli_date/errors.rb +8 -0
- data/lib/lesli_date/formatter.rb +98 -75
- data/lib/lesli_date/parser.rb +61 -0
- data/lib/lesli_date/version.rb +2 -2
- data/readme.md +206 -30
- metadata +87 -7
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
# Formatter
|
|
2
|
+
|
|
3
|
+
`LesliDate::Formatter` interprets calendar dates and instants and exposes a set of display formats. Calendar dates retain their day; instants are converted to the presentation time zone.
|
|
4
|
+
|
|
5
|
+
## Create a formatter
|
|
6
|
+
|
|
7
|
+
```ruby
|
|
8
|
+
formatter = LesliDate::Formatter.new(Time.current)
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
The constructor accepts a value, an optional positional input format, zone options, and an optional output locale:
|
|
12
|
+
|
|
13
|
+
```ruby
|
|
14
|
+
LesliDate::Formatter.new("2026/10/05 14:30", "%Y/%m/%d %H:%M")
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
| Argument | Default | Purpose |
|
|
18
|
+
| --- | --- | --- |
|
|
19
|
+
| `datetime` | `Time.current` | Date or instant to interpret; explicit `nil` is invalid |
|
|
20
|
+
| `format` | `nil` | Native Ruby `strptime` pattern; otherwise use `DateTime.parse` |
|
|
21
|
+
| `input_zone:` | `"UTC"` | Interpret date-time strings that have no offset |
|
|
22
|
+
| `zone:` | `nil` | Presentation zone; `nil` uses `Time.zone`, then `Lesli.config.datetime[:time_zone]` |
|
|
23
|
+
| `locale:` | `nil` | Output language; `nil` uses `I18n.locale` when rendering |
|
|
24
|
+
|
|
25
|
+
Lesli's database timestamps are UTC. The active Rails zone controls output;
|
|
26
|
+
normal Lesli calls need no zone keywords. `input_zone:` is available for
|
|
27
|
+
external sources that provide local times instead of UTC.
|
|
28
|
+
|
|
29
|
+
Accepted objects are `Date`, `DateTime`, `Time`, and `ActiveSupport::TimeWithZone`.
|
|
30
|
+
Strings are interpreted with Ruby's `DateTime.parse` or, when a pattern is
|
|
31
|
+
provided, `DateTime.strptime`. Accepted syntax and directives follow Ruby rather
|
|
32
|
+
than a separate LesliDate format language. See [Parsing rules](/gems/date/api/parsing)
|
|
33
|
+
for timezone behavior and errors.
|
|
34
|
+
|
|
35
|
+
```ruby
|
|
36
|
+
LesliDate::Formatter.new(
|
|
37
|
+
"2026-10-22 14:30",
|
|
38
|
+
input_zone: "America/Guatemala",
|
|
39
|
+
zone: "UTC"
|
|
40
|
+
).date_time.to_s
|
|
41
|
+
# => "22.10.2026 20:30", with output format %d.%m.%Y %H:%M
|
|
42
|
+
|
|
43
|
+
LesliDate::Formatter.new("2026-10-22").get
|
|
44
|
+
# => Date.new(2026, 10, 22)
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Select an output format
|
|
48
|
+
|
|
49
|
+
Every selector uses its matching key in `Lesli.config.datetime[:formats]`.
|
|
50
|
+
Missing or `nil` values use these fallback patterns:
|
|
51
|
+
|
|
52
|
+
| Method | Fallback pattern |
|
|
53
|
+
| --- | --- |
|
|
54
|
+
| `date` | `%d.%m.%Y` |
|
|
55
|
+
| `time` | `%H:%M` |
|
|
56
|
+
| `date_time` | `%d.%m.%Y %H:%M` |
|
|
57
|
+
| `date_words` | `%B %d, %Y` |
|
|
58
|
+
| `date_words_day` | `%A, %B %d, %Y` |
|
|
59
|
+
| `date_time_words` | `%B %d, %Y, %H:%M` |
|
|
60
|
+
| `date_time_words_pm` | `%B %d, %Y, %I:%M %p` |
|
|
61
|
+
| `date_time_words_day` | `%A, %B %d, %Y, %H:%M` |
|
|
62
|
+
|
|
63
|
+
Each selector returns the formatter:
|
|
64
|
+
|
|
65
|
+
```ruby
|
|
66
|
+
formatter.date_time_words.to_s
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Selectors change the output format of the same instance. They do not parse the
|
|
70
|
+
input again or replace `.get`. Input strings, temporal values and the host's
|
|
71
|
+
configuration are not modified. Patterns are copied at construction, so later
|
|
72
|
+
configuration edits do not change an existing formatter. `.get` exposes the
|
|
73
|
+
underlying parsed value without cloning it. Use a separate formatter for
|
|
74
|
+
independent selector state.
|
|
75
|
+
|
|
76
|
+
`to_s` uses `I18n.localize` with the selected pattern. Days, months and AM/PM use
|
|
77
|
+
the translations already loaded by Rails. LesliDate does not install or replace
|
|
78
|
+
translation data. The initializer determines the pattern and the current Rails
|
|
79
|
+
locale determines its translated words:
|
|
80
|
+
|
|
81
|
+
```ruby
|
|
82
|
+
I18n.with_locale(:es) do
|
|
83
|
+
LesliDate::Formatter.new("2026-10-22").date_words.to_s
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
LesliDate::Formatter.new("2026-10-22", locale: :es).date_words.to_s
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
`get` returns a `Date` for calendar inputs
|
|
90
|
+
and an `ActiveSupport::TimeWithZone` for instants. Selecting `.date` on an instant
|
|
91
|
+
does not discard its underlying time or fractional seconds.
|
|
92
|
+
|
|
93
|
+
Calendar dates support `date`, `date_words`, and `date_words_day`. Selecting
|
|
94
|
+
`time` or any `date_time*` format raises `LesliDate::InvalidFormat` without
|
|
95
|
+
changing the previous output format.
|
|
96
|
+
|
|
97
|
+
Invalid values and native parsing failures raise `LesliDate::ParseError`;
|
|
98
|
+
invalid zone options raise `LesliDate::InvalidTimeZone`. `InvalidFormat` is used
|
|
99
|
+
for invalid output configuration and time selectors applied to calendar dates. All inherit from
|
|
100
|
+
`LesliDate::Error < ArgumentError`.
|
|
101
|
+
|
|
102
|
+
See [Configuration](/gems/date/about/configuration) for defaults, validation,
|
|
103
|
+
locales and optional translation overrides in Lesli.
|
|
104
|
+
See [Application examples](/gems/date/api/examples) for forms, APIs and imports.
|
data/docs/api/index
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# API overview
|
|
2
|
+
|
|
3
|
+
LesliDate has two public entry points:
|
|
4
|
+
|
|
5
|
+
| API | Purpose |
|
|
6
|
+
| --- | --- |
|
|
7
|
+
| `LesliDate::Formatter` | Parse a date or time, apply the configured time zone, format it for display, or generate a formatted SQL selection |
|
|
8
|
+
| `LesliDate::Compatibility.db_now` | Return the current-timestamp SQL expression for the active database adapter |
|
|
9
|
+
|
|
10
|
+
A formatter is mutable: calling `date`, `time`, or another format selector changes the output format and returns the same formatter instance.
|
|
11
|
+
|
|
12
|
+
```ruby
|
|
13
|
+
formatter = LesliDate::Formatter.new(Time.current)
|
|
14
|
+
|
|
15
|
+
formatter.date.to_s
|
|
16
|
+
formatter.date_time_words.to_s
|
|
17
|
+
formatter.get
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
`get` returns a `Date` for calendar inputs and an `ActiveSupport::TimeWithZone`
|
|
21
|
+
for instants. Calendar dates support only date selectors; time selectors raise
|
|
22
|
+
`LesliDate::InvalidFormat`.
|
|
23
|
+
|
|
24
|
+
Use [Parsing rules](/gems/date/api/parsing) for accepted inputs, zones and errors,
|
|
25
|
+
[Formatter](/gems/date/api/formatter) for display values, and
|
|
26
|
+
[Database expressions](/gems/date/api/database) for SQL selection helpers.
|
data/docs/api/parsing.md
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
# Parsing rules
|
|
2
|
+
|
|
3
|
+
LesliDate uses Ruby's date parsers and Rails timezone conversion. It does not
|
|
4
|
+
compile input patterns or maintain its own validation rules for every field.
|
|
5
|
+
|
|
6
|
+
```ruby
|
|
7
|
+
LesliDate::Formatter.new(value, format = nil, input_zone: "UTC", zone: nil, locale: nil)
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
## Input values
|
|
11
|
+
|
|
12
|
+
| Input | Behavior | `.get` result |
|
|
13
|
+
| --- | --- | --- |
|
|
14
|
+
| No argument | Current instant | `ActiveSupport::TimeWithZone` |
|
|
15
|
+
| `Time`, `TimeWithZone`, `DateTime` | Preserve the instant and apply the presentation zone | `ActiveSupport::TimeWithZone` |
|
|
16
|
+
| `Date` | Preserve the calendar date | `Date` |
|
|
17
|
+
| String without a pattern | Use `DateTime.parse` | `Date` or `ActiveSupport::TimeWithZone` |
|
|
18
|
+
| String with a pattern | Use `DateTime.strptime` | `Date` or `ActiveSupport::TimeWithZone` |
|
|
19
|
+
| Other types, including explicit `nil` | Reject with `LesliDate::ParseError` | No value |
|
|
20
|
+
|
|
21
|
+
The native parser's metadata distinguishes a calendar date from an instant.
|
|
22
|
+
Calendar dates support `.date`, `.date_words`, and `.date_words_day`. Time
|
|
23
|
+
selectors on dates raise `LesliDate::InvalidFormat` instead of inventing an hour.
|
|
24
|
+
Selecting `.date` on an instant preserves its full underlying value in `.get`.
|
|
25
|
+
|
|
26
|
+
## Native input patterns
|
|
27
|
+
|
|
28
|
+
The second positional argument is a Ruby `strptime` pattern. It supports native
|
|
29
|
+
directives, including compound directives, month names, offsets and fractions:
|
|
30
|
+
|
|
31
|
+
```ruby
|
|
32
|
+
LesliDate::Formatter.new("22/10/2026", "%d/%m/%Y").get
|
|
33
|
+
# => Date.new(2026, 10, 22)
|
|
34
|
+
|
|
35
|
+
LesliDate::Formatter.new("22 October 2026", "%d %B %Y").date.to_s
|
|
36
|
+
LesliDate::Formatter.new("2026-10-22 14:30:45", "%F %T").date_time.to_s
|
|
37
|
+
LesliDate::Formatter.new("2026-10-22T14:30:45.123Z").date_time.to_s
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
When a pattern is supplied, LesliDate calls `strptime` directly and does not
|
|
41
|
+
retry with `parse`. An unparseable value or a mismatch raises `ParseError` with
|
|
42
|
+
the native exception as its cause.
|
|
43
|
+
|
|
44
|
+
Accepted syntax, missing-component defaults, precision, calendar conventions,
|
|
45
|
+
and tolerance follow Ruby. For example, native parsing may accept partial dates
|
|
46
|
+
or a valid prefix with trailing text. LesliDate does not add complete-input
|
|
47
|
+
validation, a directive allowlist, year bounds, encoding conversion, or manual
|
|
48
|
+
range checks. Patterns apply to string inputs; temporal objects are used directly.
|
|
49
|
+
|
|
50
|
+
## UTC input and active output zone
|
|
51
|
+
|
|
52
|
+
Lesli stores database timestamps in UTC. Output uses an explicit `zone:`, then
|
|
53
|
+
the active Rails `Time.zone`, then `Lesli.config.datetime[:time_zone]` if no Rails
|
|
54
|
+
zone is active. Core sets the active zone from the profile or application default.
|
|
55
|
+
Normal Lesli calls need no zone options:
|
|
56
|
+
|
|
57
|
+
```ruby
|
|
58
|
+
# With America/Guatemala and output format %d/%m/%Y %H:%M:
|
|
59
|
+
LesliDate::Formatter.new("2026-10-22 14:30:00").date_time.to_s
|
|
60
|
+
# => "22/10/2026 08:30"
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
For strings containing a time but no offset, `input_zone` defaults to UTC.
|
|
64
|
+
Strings with an explicit offset already determine an instant. `zone` overrides
|
|
65
|
+
the configured presentation zone for one formatter. Dates do not undergo zone
|
|
66
|
+
conversion.
|
|
67
|
+
|
|
68
|
+
```ruby
|
|
69
|
+
# An external source supplies local Guatemala time rather than UTC.
|
|
70
|
+
LesliDate::Formatter.new(
|
|
71
|
+
"22/10/2026 14:30",
|
|
72
|
+
"%d/%m/%Y %H:%M",
|
|
73
|
+
input_zone: "America/Guatemala",
|
|
74
|
+
zone: "UTC"
|
|
75
|
+
).date_time.to_s
|
|
76
|
+
# => "22.10.2026 20:30", with output format %d.%m.%Y %H:%M
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Zone names use `ActiveSupport::TimeZone`. Local times, including clock-change
|
|
80
|
+
gaps and overlaps, follow Rails' native `TimeZone#local` behavior. LesliDate does
|
|
81
|
+
not implement a separate daylight-saving validation policy.
|
|
82
|
+
|
|
83
|
+
## Exceptions
|
|
84
|
+
|
|
85
|
+
| Error | Meaning |
|
|
86
|
+
| --- | --- |
|
|
87
|
+
| `LesliDate::ParseError` | Unsupported input type or an exception from native parsing |
|
|
88
|
+
| `LesliDate::InvalidTimeZone` | Missing or unknown zone name; an unsupported SQLite output zone when generating SQL |
|
|
89
|
+
| `LesliDate::InvalidFormat` | Invalid output configuration, a time selector applied to a calendar date, or an unsupported PostgreSQL SQL-format directive |
|
|
90
|
+
|
|
91
|
+
All inherit from `LesliDate::Error < ArgumentError`.
|
|
92
|
+
I18n locale/translation failures keep their native exception behavior. SQL
|
|
93
|
+
execution errors come from ActiveRecord; unsupported SQLite format directives
|
|
94
|
+
return native SQL `NULL` rather than a LesliDate exception.
|
|
95
|
+
|
|
96
|
+
```ruby
|
|
97
|
+
begin
|
|
98
|
+
value = LesliDate::Formatter.new(params[:date], "%d/%m/%Y").get
|
|
99
|
+
rescue LesliDate::ParseError
|
|
100
|
+
# Present the application's validation message.
|
|
101
|
+
end
|
|
102
|
+
```
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" fill="#0c2856" viewBox="0 0 100 100"><desc>A formatted calendar paired with a clock.</desc><rect width="61" height="67" x="8" y="19" rx="7"/><rect width="49" height="43" x="14" y="35" fill="#d8e1ef" rx="3"/><rect width="8" height="18" x="20" y="12" rx="4"/><rect width="8" height="18" x="48" y="12" rx="4"/><rect width="9" height="8" x="20" y="43" rx="2"/><rect width="9" height="8" x="34" y="43" rx="2"/><rect width="9" height="8" x="48" y="43" rx="2"/><rect width="9" height="8" x="20" y="57" rx="2"/><rect width="9" height="8" x="34" y="57" rx="2"/><circle cx="73" cy="68" r="21"/><circle cx="73" cy="68" r="14" fill="#d8e1ef"/><path d="M70 56h6v11l8 5-3 5-11-7Z"/></svg>
|
data/docs/navigation
ADDED
data/lib/lesli_date/formatter.rb
CHANGED
|
@@ -32,14 +32,33 @@ Building a better future, one line of code at a time.
|
|
|
32
32
|
|
|
33
33
|
# maybe move this to a "LDate" gem?
|
|
34
34
|
|
|
35
|
+
require "lesli_date/parser"
|
|
36
|
+
require "active_record"
|
|
37
|
+
require "i18n"
|
|
38
|
+
|
|
35
39
|
module LesliDate
|
|
36
40
|
class Formatter
|
|
37
41
|
|
|
38
|
-
|
|
42
|
+
DEFAULT_FORMATS = {
|
|
43
|
+
:date => "%d.%m.%Y",
|
|
44
|
+
:time => "%H:%M",
|
|
45
|
+
:date_time => "%d.%m.%Y %H:%M",
|
|
46
|
+
:date_words => "%B %d, %Y", # date in words including day's name
|
|
47
|
+
:date_words_day => "%A, %B %d, %Y", # date in words including day's name
|
|
48
|
+
:date_time_words => "%B %d, %Y, %H:%M", # 24 hours datetime in words format (default)
|
|
49
|
+
:date_time_words_pm => "%B %d, %Y, %I:%M %p", # 12 hours datetime in words format
|
|
50
|
+
:date_time_words_day => "%A, %B %d, %Y, %H:%M", # 24 hours datetime in words format (default)
|
|
51
|
+
}.freeze
|
|
52
|
+
private_constant :DEFAULT_FORMATS
|
|
53
|
+
|
|
54
|
+
def initialize(datetime = Time.current, format = nil, input_zone: "UTC", zone: nil, locale: nil)
|
|
39
55
|
|
|
40
56
|
# NOTE: user should be able to change this through settings table
|
|
41
57
|
# get initial datetime configuration
|
|
42
|
-
config = Lesli.config.datetime
|
|
58
|
+
config = Lesli.config.datetime || {}
|
|
59
|
+
output_zone = zone.nil? ? (Time.zone&.name || config[:time_zone]) : zone
|
|
60
|
+
# Core applies the profile or application zone; input timestamps remain UTC.
|
|
61
|
+
@parser = Parser.new(input_zone: input_zone, zone: output_zone)
|
|
43
62
|
|
|
44
63
|
|
|
45
64
|
# NOTE: Do not modify settings here,
|
|
@@ -63,19 +82,11 @@ module LesliDate
|
|
|
63
82
|
# }
|
|
64
83
|
|
|
65
84
|
@settings = {
|
|
66
|
-
:time_zone =>
|
|
67
|
-
:start_week_on => config[:start_week_on],
|
|
68
|
-
:format =>
|
|
69
|
-
:date => config[:formats][:date] || "%d.%m.%Y",
|
|
70
|
-
:time => "%H:%M",
|
|
71
|
-
:date_time => config[:formats][:date_time] || "%d.%m.%Y %H:%M",
|
|
72
|
-
:date_words => "%B %d, %Y", # date in words including day's name
|
|
73
|
-
:date_words_day => "%A, %B %d, %Y", # date in words including day's name
|
|
74
|
-
:date_time_words => "%B %d, %Y, %H:%M", # 24 hours datetime in words format (default)
|
|
75
|
-
:date_time_words_pm => "%B %d, %Y, %I:%M %p", # 12 hours datetime in words format
|
|
76
|
-
:date_time_words_day => "%A, %B %d, %Y, %H:%M", # 24 hours datetime in words format (default)
|
|
77
|
-
}
|
|
85
|
+
:time_zone => @parser.output_zone.name,
|
|
86
|
+
:start_week_on => config[:start_week_on] || "monday",
|
|
87
|
+
:format => configured_formats(config[:formats])
|
|
78
88
|
}
|
|
89
|
+
@locale = locale
|
|
79
90
|
|
|
80
91
|
|
|
81
92
|
# default date format
|
|
@@ -83,25 +94,16 @@ module LesliDate
|
|
|
83
94
|
|
|
84
95
|
|
|
85
96
|
# get a valid timezone
|
|
86
|
-
@zone =
|
|
97
|
+
@zone = @parser.output_zone
|
|
87
98
|
|
|
88
99
|
|
|
89
100
|
# get datetime object from user params
|
|
90
|
-
@datetime = parse_initial_datetime(datetime, format)
|
|
101
|
+
@datetime = parse_initial_datetime(datetime, format)
|
|
91
102
|
|
|
92
103
|
end
|
|
93
104
|
|
|
94
105
|
# Dynamically define formatting methods like `date`, `time`, etc.
|
|
95
|
-
|
|
96
|
-
:date,
|
|
97
|
-
:time,
|
|
98
|
-
:date_time,
|
|
99
|
-
:date_words,
|
|
100
|
-
:date_words_day,
|
|
101
|
-
:date_time_words,
|
|
102
|
-
:date_time_words_pm,
|
|
103
|
-
:date_time_words_day
|
|
104
|
-
].each do |key|
|
|
106
|
+
DEFAULT_FORMATS.each_key do |key|
|
|
105
107
|
define_method(key) do
|
|
106
108
|
set_format(key)
|
|
107
109
|
self
|
|
@@ -110,47 +112,43 @@ module LesliDate
|
|
|
110
112
|
|
|
111
113
|
# return query string to get timestamps columns from database
|
|
112
114
|
def db_timestamps table=""
|
|
113
|
-
|
|
114
|
-
# avoid ambiguous columns
|
|
115
|
-
table = table.concat(".") if table != ""
|
|
116
|
-
|
|
117
|
-
# get right format for dates
|
|
118
|
-
format = self.db_format
|
|
119
|
-
|
|
120
|
-
# compatibility for SQLite
|
|
121
|
-
if ActiveRecord::Base.connection.adapter_name == "SQLite"
|
|
122
|
-
offset = ActiveSupport::TimeZone[@settings[:time_zone]].utc_offset / 3600
|
|
123
|
-
return "strftime('#{format}', #{table}created_at, '#{offset} hours') as created_at_string"
|
|
124
|
-
end
|
|
125
|
-
|
|
126
|
-
"TO_CHAR(#{table}created_at at time zone 'utc' at time zone '#{@settings[:time_zone]}', '#{format}') as created_at_date, TO_CHAR(#{table}updated_at at time zone 'utc' at time zone '#{@settings[:time_zone]}', '#{format}') as updated_at_date"
|
|
127
|
-
|
|
115
|
+
[:created_at, :updated_at].map { |column| db_column(column, table) }.join(", ")
|
|
128
116
|
end
|
|
129
117
|
|
|
130
118
|
# return query string to get a datetime column from database
|
|
131
119
|
def db_column column, table="", as:nil
|
|
132
|
-
|
|
133
|
-
as = "#{column}_string" unless as
|
|
120
|
+
connection = ActiveRecord::Base.connection
|
|
134
121
|
|
|
135
122
|
# avoid ambiguous columns
|
|
136
|
-
|
|
123
|
+
identifier = connection.quote_column_name(column.to_s)
|
|
124
|
+
identifier = "#{connection.quote_table_name(table.to_s)}.#{identifier}" unless table.to_s.empty?
|
|
137
125
|
|
|
138
126
|
# get right format for dates
|
|
139
|
-
format =
|
|
127
|
+
format = connection.quote(db_format)
|
|
140
128
|
|
|
141
129
|
# compatibility for SQLite
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
130
|
+
case connection.adapter_name
|
|
131
|
+
when "SQLite"
|
|
132
|
+
# SQLite supports fixed offsets, including fractional hours, but not IANA rules.
|
|
133
|
+
period = @zone.tzinfo.period_for_utc(Time.current.utc)
|
|
134
|
+
raise InvalidTimeZone, "SQLite requires a fixed output offset; use UTC or format #{@zone.name} in Ruby" if period.ends_at
|
|
135
|
+
|
|
136
|
+
offset = connection.quote("#{period.observed_utc_offset} seconds")
|
|
137
|
+
sql = "strftime(#{format}, #{identifier}, #{offset})"
|
|
138
|
+
when "PostgreSQL"
|
|
139
|
+
zone = connection.quote(@zone.tzinfo.identifier)
|
|
140
|
+
sql = "TO_CHAR(#{identifier} AT TIME ZONE 'UTC' AT TIME ZONE #{zone}, #{format})"
|
|
141
|
+
else
|
|
142
|
+
raise NotImplementedError, "LesliDate SQL does not support #{connection.adapter_name}"
|
|
145
143
|
end
|
|
146
144
|
|
|
147
|
-
|
|
148
|
-
|
|
145
|
+
return sql if as == false
|
|
146
|
+
"#{sql} AS #{connection.quote_column_name((as || "#{column}_string").to_s)}"
|
|
149
147
|
end
|
|
150
148
|
|
|
151
149
|
# convert a datetime object to string representation using defined format
|
|
152
150
|
def to_s
|
|
153
|
-
|
|
151
|
+
I18n.localize(@datetime, format: @format, locale: @locale)
|
|
154
152
|
end
|
|
155
153
|
|
|
156
154
|
def get
|
|
@@ -159,43 +157,68 @@ module LesliDate
|
|
|
159
157
|
|
|
160
158
|
private
|
|
161
159
|
|
|
160
|
+
def configured_formats(formats)
|
|
161
|
+
formats = {} if formats.nil?
|
|
162
|
+
raise InvalidFormat, "datetime[:formats] must be a hash" unless formats.is_a?(Hash)
|
|
162
163
|
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
164
|
+
DEFAULT_FORMATS.merge(formats.compact).to_h do |name, pattern|
|
|
165
|
+
unless pattern.is_a?(String) && pattern.valid_encoding? && !pattern.strip.empty?
|
|
166
|
+
raise InvalidFormat, "Format #{name} must be a nonempty string"
|
|
167
|
+
end
|
|
167
168
|
|
|
168
|
-
|
|
169
|
-
return ::DateTime.iso8601(datetime)
|
|
169
|
+
[name, validated_format(pattern)]
|
|
170
170
|
end
|
|
171
|
+
end
|
|
171
172
|
|
|
172
|
-
|
|
173
|
+
def validated_format(pattern)
|
|
174
|
+
Time.current.strftime(pattern)
|
|
175
|
+
pattern.dup.freeze
|
|
176
|
+
rescue ArgumentError => error
|
|
177
|
+
raise InvalidFormat, error.message
|
|
173
178
|
end
|
|
174
179
|
|
|
175
180
|
|
|
176
|
-
|
|
177
|
-
|
|
181
|
+
# get datetime object or string datetime and return a datetime object
|
|
182
|
+
def parse_initial_datetime datetime, format
|
|
183
|
+
# Calendar dates remain Dates; the parser converts only instants.
|
|
184
|
+
@parser.parse(datetime, format)
|
|
178
185
|
end
|
|
179
186
|
|
|
180
187
|
|
|
181
|
-
def
|
|
182
|
-
format
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
return format if ActiveRecord::Base.connection.adapter_name == "SQLite"
|
|
188
|
+
def set_format format
|
|
189
|
+
if @datetime.is_a?(::Date) && ![:date, :date_words, :date_words_day].include?(format || :date)
|
|
190
|
+
raise InvalidFormat, "A calendar date cannot be formatted with a time selector"
|
|
191
|
+
end
|
|
186
192
|
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
format = format.gsub("%m", "MM")
|
|
190
|
-
format = format.gsub("%d", "DD")
|
|
193
|
+
@format = @settings[:format][format || :date]
|
|
194
|
+
end
|
|
191
195
|
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
format
|
|
195
|
-
|
|
196
|
-
|
|
196
|
+
def db_format
|
|
197
|
+
# SQLite format dates are the same of ruby format
|
|
198
|
+
return @format if ActiveRecord::Base.connection.adapter_name == "SQLite"
|
|
199
|
+
|
|
200
|
+
formats = {
|
|
201
|
+
# Convert Ruby to postgresql date format
|
|
202
|
+
"%Y" => "YYYY", "%y" => "YY", "%m" => "MM", "%d" => "DD",
|
|
203
|
+
"%B" => "FMMonth", "%b" => "FMMon", "%A" => "FMDay", "%a" => "FMDy",
|
|
204
|
+
"%j" => "DDD", "%F" => "YYYY-MM-DD",
|
|
205
|
+
# Convert Ruby to postgresql time format
|
|
206
|
+
"%H" => "HH24", # 24 hours format
|
|
207
|
+
"%I" => "HH12", # 12 hours format
|
|
208
|
+
"%p" => "AM", # Meridian indicator (AM/PM)
|
|
209
|
+
"%P" => "am", "%M" => "MI", "%S" => "SS",
|
|
210
|
+
"%R" => "HH24:MI", "%T" => "HH24:MI:SS", "%%" => '"%"'
|
|
211
|
+
}
|
|
197
212
|
|
|
198
|
-
format
|
|
213
|
+
@format.gsub(/%.|[^%]+|%/) do |part|
|
|
214
|
+
if part.start_with?("%")
|
|
215
|
+
formats.fetch(part) { raise InvalidFormat, "PostgreSQL does not support #{part.inspect}" }
|
|
216
|
+
else
|
|
217
|
+
# Quoted text stays literal inside PostgreSQL's format template.
|
|
218
|
+
'"' + part.gsub(/["\\]/) { |character| "\\#{character}" } + '"'
|
|
219
|
+
end
|
|
220
|
+
end
|
|
199
221
|
end
|
|
222
|
+
|
|
200
223
|
end
|
|
201
224
|
end
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "active_support"
|
|
4
|
+
require "active_support/time"
|
|
5
|
+
require "lesli_date/errors"
|
|
6
|
+
|
|
7
|
+
module LesliDate
|
|
8
|
+
# Calendar dates remain Dates; only instants undergo timezone conversion.
|
|
9
|
+
class Parser
|
|
10
|
+
attr_reader :output_zone
|
|
11
|
+
|
|
12
|
+
def initialize(input_zone:, zone:)
|
|
13
|
+
@output_zone = resolve_zone(zone)
|
|
14
|
+
@input_zone = resolve_zone(input_zone)
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
def parse(value, format = nil)
|
|
18
|
+
case value
|
|
19
|
+
when String
|
|
20
|
+
parse_string(value, format)
|
|
21
|
+
when Time, ActiveSupport::TimeWithZone
|
|
22
|
+
value.in_time_zone(@output_zone)
|
|
23
|
+
when DateTime
|
|
24
|
+
value.new_start(Date::GREGORIAN).in_time_zone(@output_zone)
|
|
25
|
+
when Date
|
|
26
|
+
value
|
|
27
|
+
else
|
|
28
|
+
raise ParseError, "Expected a date, time or date string"
|
|
29
|
+
end
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
private
|
|
33
|
+
|
|
34
|
+
def resolve_zone(name)
|
|
35
|
+
zone = ActiveSupport::TimeZone[name] if name.is_a?(String)
|
|
36
|
+
zone || raise(InvalidTimeZone, "Unknown time zone: #{name.inspect}")
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
def parse_string(value, format)
|
|
40
|
+
value = value.strip
|
|
41
|
+
datetime = format ? DateTime.strptime(value, format) : DateTime.parse(value)
|
|
42
|
+
parts = format ? Date._strptime(value, format) : Date._parse(value)
|
|
43
|
+
|
|
44
|
+
# Native parsing metadata distinguishes a date from a time or explicit offset.
|
|
45
|
+
return datetime.to_date if (parts.keys & [:hour, :min, :sec, :seconds, :offset]).empty?
|
|
46
|
+
|
|
47
|
+
if parts[:offset] || parts[:seconds]
|
|
48
|
+
return datetime.new_start(Date::GREGORIAN).in_time_zone(@output_zone)
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
@input_zone.local(
|
|
52
|
+
datetime.year, datetime.month, datetime.day,
|
|
53
|
+
datetime.hour, datetime.minute, datetime.second + datetime.sec_fraction
|
|
54
|
+
).in_time_zone(@output_zone)
|
|
55
|
+
rescue ArgumentError, TypeError => error
|
|
56
|
+
raise ParseError, error.message
|
|
57
|
+
end
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
private_constant :Parser
|
|
61
|
+
end
|
data/lib/lesli_date/version.rb
CHANGED