FormatDateTimeWithBC formats a time.Time that may represent BC dates (negative years) PostgreSQL represents BC years as negative years in time.Time, but Go's Format() doesn't handle this correctly tz is optional timezone value to be appended to formatted value
(t time.Time, layout string, hasTZ bool)
| 226 | // PostgreSQL represents BC years as negative years in time.Time, but Go's Format() doesn't handle this correctly |
| 227 | // tz is optional timezone value to be appended to formatted value |
| 228 | func FormatDateTimeWithBC(t time.Time, layout string, hasTZ bool) string { |
| 229 | year := t.Year() |
| 230 | isBC := year <= 0 |
| 231 | |
| 232 | var formattedTime string |
| 233 | if isBC { |
| 234 | // Convert from PostgreSQL's BC representation to positive year for formatting |
| 235 | // PostgreSQL: year 0 = 1 BC, year -1 = 2 BC, etc. |
| 236 | absYear := 1 - year |
| 237 | |
| 238 | // Create a new time with the positive year for formatting |
| 239 | positiveTime := time.Date(absYear, t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), t.Location()) |
| 240 | |
| 241 | // Convert the negative year to positive year to get formatted result, but it creates issue on |
| 242 | // the day of week value, so we need to get day of the week value from original negative time value. |
| 243 | if strings.HasPrefix(layout, "Mon") { |
| 244 | formattedTime = fmt.Sprintf("%s%s", t.Format("Mon"), positiveTime.Format(strings.TrimPrefix(layout, "Mon"))) |
| 245 | } else { |
| 246 | // Format with the positive year, then append " BC" |
| 247 | formattedTime = positiveTime.Format(layout) |
| 248 | } |
| 249 | } else { |
| 250 | // For AD years (positive), use normal formatting |
| 251 | formattedTime = t.Format(layout) |
| 252 | } |
| 253 | |
| 254 | if hasTZ { |
| 255 | name, offset := t.Zone() |
| 256 | if strings.HasPrefix(layout, "Mon") { |
| 257 | // Postgres doesn't show timezone for ones that don't have timezone abbreviation. |
| 258 | if name != "" { |
| 259 | name = t.Format("MST") |
| 260 | } |
| 261 | formattedTime += fmt.Sprintf(" %s", name) |
| 262 | } else { |
| 263 | if offset%3600 != 0 { |
| 264 | formattedTime += t.Format("-07:00") |
| 265 | } else { |
| 266 | formattedTime += t.Format("-07") |
| 267 | } |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | if isBC { |
| 272 | return formattedTime + " BC" |
| 273 | } |
| 274 | return formattedTime |
| 275 | } |
no test coverage detected