|
13 | 13 | // limitations under the License.
|
14 | 14 |
|
15 | 15 | // Package time defines time-related types.
|
| 16 | +// |
| 17 | +// In CUE time values are represented as a string of the format |
| 18 | +// time.RFC3339Nano. |
16 | 19 | package time
|
17 | 20 |
|
18 | 21 | import (
|
@@ -146,6 +149,17 @@ func Format(value, layout string) (bool, error) {
|
146 | 149 | return timeFormat(value, layout)
|
147 | 150 | }
|
148 | 151 |
|
| 152 | +// FormatString returns a textual representation of the time value. |
| 153 | +// The formatted value is formatted according to the layout defined by the |
| 154 | +// argument. See Parse for more information on the layout string. |
| 155 | +func FormatString(layout, value string) (string, error) { |
| 156 | + t, err := time.Parse(time.RFC3339Nano, value) |
| 157 | + if err != nil { |
| 158 | + return "", err |
| 159 | + } |
| 160 | + return t.Format(layout), nil |
| 161 | +} |
| 162 | + |
149 | 163 | // Parse parses a formatted string and returns the time value it represents.
|
150 | 164 | // The layout defines the format by showing how the reference time,
|
151 | 165 | // defined to be
|
@@ -196,3 +210,35 @@ func Unix(sec int64, nsec int64) string {
|
196 | 210 | t := time.Unix(sec, nsec)
|
197 | 211 | return t.UTC().Format(time.RFC3339Nano)
|
198 | 212 | }
|
| 213 | + |
| 214 | +// Parts holds individual parts of a parsed time stamp. |
| 215 | +type Parts struct { |
| 216 | + Year int `json:"year"` |
| 217 | + Month int `json:"month"` |
| 218 | + Day int `json:"day"` |
| 219 | + Hour int `json:"hour"` |
| 220 | + Minute int `json:"minute"` |
| 221 | + |
| 222 | + // Second is equal to div(Nanosecond, 1_000_000_000) |
| 223 | + Second int `json:"second"` |
| 224 | + Nanosecond int `json:"nanosecond"` |
| 225 | +} |
| 226 | + |
| 227 | +// Split parses a time string into its individual parts. |
| 228 | +func Split(t string) (*Parts, error) { |
| 229 | + st, err := time.Parse(time.RFC3339Nano, t) |
| 230 | + if err != nil { |
| 231 | + return nil, err |
| 232 | + } |
| 233 | + year, month, day := st.Date() |
| 234 | + return &Parts{ |
| 235 | + Year: year, |
| 236 | + Month: int(month), |
| 237 | + Day: day, |
| 238 | + Hour: st.Hour(), |
| 239 | + Minute: st.Minute(), |
| 240 | + |
| 241 | + Second: st.Second(), |
| 242 | + Nanosecond: st.Nanosecond(), |
| 243 | + }, nil |
| 244 | +} |
0 commit comments