Taskcore
Parse and format a date
Also called parse an ISO 8601 timestamp, parse an RFC 3339 date-time, convert a timestamp to UTC, format a date as ISO 8601.
Parse an RFC 3339 date-time with a UTC offset, reject text that is not valid, and print the same instant in UTC with exactly three fraction digits.
- Evidence
- Code in 10 languages
Task
Read a timestamp in the date-time format of RFC 3339, for example 2026-11-10T19:30:00+07:00. Print the same instant in UTC, as 2026-11-10T12:30:00.000Z.
Each solution is a function to_utc(timestamp) that returns a string. The result has the form YYYY-MM-DDTHH:MM:SS.sssZ, with exactly three fraction digits. This is the form of JavaScript toISOString. When the input is not valid, the function reports an error and returns no result.
The input syntax is the date-time rule of RFC 3339 section 5.6. A date-time has a full date, the letter T, a time with seconds, an optional fraction, and an offset. The offset is Z for UTC, or a sign, two digits of hours, a colon and two digits of minutes. The hour is from 00 to 23. The day must exist in the month and the year, as the table of section 5.7 gives. Section 5.6 also lets T and Z be lower case, so 2026-11-10t12:00:00z is valid.
The contract has three limits that RFC 3339 does not have. The fraction has 1 to 3 digits. The offset is from -14:00 to +14:00, because .NET DateTimeOffset rejects an offset of more than 14 hours. The year of the input and the year of the result are from 0001 to 9999.
RFC 3339 section 4.2 calculates an offset as local time minus UTC. So the solution subtracts the offset: 19:30+07:00 is 12:30Z. The time zone of the machine has no effect. Each test passes with any value of TZ.
Solutions
Each solution checks the syntax first, and then it checks the calendar. A library parser alone is not sufficient, because each one accepts some text that RFC 3339 does not allow (see Pitfalls).
- Python. A pattern checks the syntax with
re.fullmatch. The pattern uses[0-9], because\dalso matches digits of other scripts.datetime.fromisoformatthen makes an awaredatetime, and it raisesValueErrorfor a day that is not in the calendar.astimezone(timezone.utc)changes the offset, andisoformat(timespec="milliseconds")gives three fraction digits. - JavaScript and TypeScript (Node.js). A pattern checks the syntax, and a table of month lengths checks the day.
new Date(text)then parses the instant, andtoISOStringprints it in UTC. The day check is necessary, becauseDatecan move an invalid day into the next month. The TypeScript file adds types only. - Java. A
Patternchecks the syntax.OffsetDateTime.parsewithDateTimeFormatter.ISO_OFFSET_DATE_TIMEparses the text. That formatter usesResolverStyle.STRICT, so it rejects a day that is not valid for the month.withOffsetSameInstant(ZoneOffset.UTC)changes the offset, and the patternuuuu-MM-dd'T'HH:mm:ss.SSS'Z'prints the result. - C#. A regular expression checks the syntax. It uses
[0-9]and\z, because\dmatches all Unicode decimal digits and$also matches before a final line end.DateTimeOffset.ParseExactwith the formatsyyyy-MM-dd'T'HH:mm:ss.FFFzzzandyyyy-MM-dd'T'HH:mm:ss.FFF'Z'parses the text. The second format has no offset specifier, so the call usesDateTimeStyles.AssumeUniversal, which gives the offset +00:00. With no style, the parser uses the offset of the local time zone. - Go. A
regexpchecks the syntax, andtime.Parse(time.RFC3339, s)parses the text. It rejects a day that is not in the month. The layout2006-01-02T15:04:05.000Z07:00prints the result. In a layout, aZin place of the sign printsZfor UTC. - Rust.
std::timehasDuration,InstantandSystemTime, and no calendar type. So the solution reads the digits by hand and counts days with thedays_from_civilandcivil_from_daysalgorithms of Howard Hinnant. These algorithms start the year on 1 March, so the leap day is the last day of a year. The function returnsResult<String, ParseError>. - C. The same hand parser and the same day algorithms. The function writes to a buffer of
TO_UTC_SIZEbytes and returns 0, or it returns -1 for an error. A division in C truncates toward zero, so afloor_divfunction rounds the days down for an instant before 1970. - C++.
std::regexchecks the syntax.std::chrono::year_month_day::ok()is false for a date that is not in the calendar.sys_daysadds the time and subtracts the offset.std::format("{:%FT%T}Z", t)prints the result:%Fis%Y-%m-%d, and%Tprints the seconds with three digits for asys_time<milliseconds>. The function returnsstd::expected<std::string, std::string>. - Bash.
[[ $ts =~ $pattern ]]matches a POSIX extended regular expression, andBASH_REMATCHholds the groups. The10#prefix reads08as eight, because a constant with a leading 0 is octal. Shell arithmetic then counts the days with the algorithms of Hinnant. The script does not usedate, because its options to parse a date are different on each system: GNUdatehas-d, and BSDdatehas-jand-f. The function prints an error to standard error and returns status 1.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl. The inputs that must give an error are in cases/errors.jsonl, and each test file holds them by name.
back-a-day,forward-a-dayandyear-end: the offset moves the instant across midnight, and across the end of 2026.leap-day: 2024-02-29 is valid, and the offset moves it to 1 March.half-hour-offsetandquarter-hour-offset: offsets such as+05:30and+05:45have minutes.unknown-offset: RFC 3339 section 4.3 uses-00:00when the time in UTC is known and the local offset is not. It is the same instant asZ.fraction-one-digitandfraction-three-digits:.5becomes.500.before-epochandbefore-epoch-fraction: instants before 1970 are negative numbers. Each solution must round the day down, not toward zero.largest-offsetandsmallest-offset:+14:00and-12:00.lower-case:tandzare valid.space-separator: section 5.6 says that an application can choose a space in place ofTfor readability. This contract does not make that choice, so a space is an error.year-oneandyear-9999: the year has four digits, also when it is 0001.- The errors: no offset, a date only, no seconds,
+0700,+07, 2026-02-29, 2026-04-31, month 13, day 0, hour 24, minute 60, offset hour 24, offset minute 60, a comma before the fraction, a space at the end, and the empty string. leap-second: section 5.7 lets the second be 60 at the end of a month with a leap second. The library parsers reject it (see Pitfalls), so the contract makes it an error for each solution.
Pitfalls
- A timestamp with no offset. The value is then not one instant. Python makes a naive
datetime, andastimezonepresumes that a naive value is in the time zone of the system. The same text gives two instants in two zones:
This code runs but gives a wrong answer on purpose.
import os
import time
from datetime import datetime, timezone
for zone in ["Asia/Ho_Chi_Minh", "America/New_York"]:
os.environ["TZ"] = zone
time.tzset()
value = datetime.fromisoformat("2026-11-10T12:00:00")
print(zone, value.tzinfo, value.astimezone(timezone.utc).isoformat())
Asia/Ho_Chi_Minh None 2026-11-10T05:00:00+00:00
America/New_York None 2026-11-10T17:00:00+00:00
JavaScript has a second rule. With no offset, a date-only form is UTC and a date-time form is local time:
This code runs but gives a wrong answer on purpose.
process.env.TZ = "America/New_York";
console.log(new Date("2026-11-10").toISOString());
console.log(new Date("2026-11-10T00:00:00").toISOString());
2026-11-10T00:00:00.000Z
2026-11-10T05:00:00.000Z
Require the offset, or write down which zone the text is in and give that zone to the parser.
- A day that does not exist. MDN says that implementations behave inconsistently for a date such as 30 February. Node.js moves it into March:
This code runs but gives a wrong answer on purpose.
console.log(new Date("2026-02-30T12:00:00Z").toISOString());
console.log(new Date("2026-04-31T12:00:00Z").toISOString());
2026-03-02T12:00:00.000Z
2026-05-01T12:00:00.000Z
- A parser that accepts too much. The Go documentation says that
time.RFC3339withtime.Parsedoes not accept all the formats of the RFC, and that it accepts some formats that the RFC does not define:
This code runs but gives a wrong answer on purpose.
package main
import (
"fmt"
"time"
)
func main() {
for _, s := range []string{
"2026-11-10T12:00:00+24:00",
"2026-11-10T12:00:00+07:60",
"2026-11-10T12:00:00,5Z",
} {
t, err := time.Parse(time.RFC3339, s)
fmt.Println(s, "->", t.UTC().Format(time.RFC3339Nano), err)
}
}
2026-11-10T12:00:00+24:00 -> 2026-11-09T12:00:00Z <nil>
2026-11-10T12:00:00+07:60 -> 2026-11-10T04:00:00Z <nil>
2026-11-10T12:00:00,5Z -> 2026-11-10T12:00:00.5Z <nil>
Python fromisoformat accepts any valid ISO 8601 form, with some exceptions, so it also accepts text that is not RFC 3339:
This code runs but gives a wrong answer on purpose.
from datetime import datetime
for text in ["2026-11-10T24:00:00+0700", "2026-11-10 12:00Z", "20261110T120000Z"]:
print(text, "->", datetime.fromisoformat(text).isoformat())
2026-11-10T24:00:00+0700 -> 2026-11-11T00:00:00+07:00
2026-11-10 12:00Z -> 2026-11-10T12:00:00+00:00
20261110T120000Z -> 2026-11-10T12:00:00+00:00
Check the syntax with a strict pattern before the call.
- The wrong pattern letter. The letters of a format are short, and a wrong letter gives a value that looks correct. In Java,
Yis the week-based year, anduis the year:
This code runs but gives a wrong answer on purpose.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2026, 12, 28);
System.out.println(date.format(DateTimeFormatter.ofPattern("YYYY-MM-dd", Locale.ROOT)));
System.out.println(date.format(DateTimeFormatter.ofPattern("uuuu-MM-dd", Locale.ROOT)));
}
}
2027-12-28
2026-12-28
In .NET, mm is the minute, and MM is the month:
This code runs but gives a wrong answer on purpose.
using System.Globalization;
var value = new DateTime(2026, 11, 10, 12, 34, 56, DateTimeKind.Utc);
Console.WriteLine(value.ToString("yyyy-mm-dd", CultureInfo.InvariantCulture));
Console.WriteLine(value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture));
2026-34-10
2026-11-10
A Go layout is the reference time Mon Jan 2 15:04:05 MST 2006, written in the form to print. Text that is not part of the reference time is printed with no change:
This code runs but gives a wrong answer on purpose.
package main
import (
"fmt"
"time"
)
func main() {
t := time.Date(2026, 11, 10, 12, 0, 0, 0, time.UTC)
fmt.Println(t.Format("YYYY-MM-DD"))
fmt.Println(t.Format("2006-01-02"))
}
YYYY-MM-DD
2026-11-10
- The leap second. RFC 3339 allows
23:59:60, but the parsers of Python, JavaScript, Java, C# and Go reject it. Python gives this error:
from datetime import datetime
try:
datetime.fromisoformat("2016-12-31T23:59:60+00:00")
except ValueError as error:
print("ValueError:", error)
ValueError: second must be in 0..59, not 60
Related tasks
- Sort a list of records: sort records by an instant. Text with different offsets does not sort in time order, so convert each value to UTC first.
- Read an environment variable:
TZis an environment variable, and the tests do not depend on it. - Split a string: split a line into fields before you parse the date in one of them.
- Parse command-line arguments: read a timestamp from the command line.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/parse-and-format-a-date/.
import re
from datetime import datetime, timezone
# The date-time of RFC 3339 section 5.6, with a fraction of 1 to 3 digits.
# fromisoformat accepts more than this (24:00, +0700, a space for T), so the
# pattern checks the syntax first. [0-9] is ASCII only; \d also matches other
# digits.
RFC3339 = re.compile(
r"[0-9]{4}-[0-9]{2}-[0-9]{2}[Tt]"
r"([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\.[0-9]{1,3})?"
r"([Zz]|[+-]([01][0-9]|2[0-3]):[0-5][0-9])"
)
def to_utc(timestamp: str) -> str:
"""Return the instant of an RFC 3339 timestamp in UTC, as YYYY-MM-DDTHH:MM:SS.sssZ.
Raise ValueError when timestamp is not an RFC 3339 date-time with an
offset, or when its date is not in the calendar.
"""
if RFC3339.fullmatch(timestamp) is None:
raise ValueError(f"not an RFC 3339 date-time: {timestamp!r}")
# The pattern makes sure that there is an offset, so the value is aware.
# fromisoformat checks the calendar: 2026-02-29 raises ValueError.
value = datetime.fromisoformat(timestamp.upper())
text = value.astimezone(timezone.utc).isoformat(timespec="milliseconds")
return text.removesuffix("+00:00") + "Z"
test_to_utc.py 65 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/parse-and-format-a-date/.
import pytest
from to_utc import to_utc
# name: (input, expected value)
CASES = {
"utc": ("2026-11-10T12:00:00Z", "2026-11-10T12:00:00.000Z"),
"positive-offset": ("2026-11-10T19:30:00+07:00", "2026-11-10T12:30:00.000Z"),
"negative-offset": ("2026-11-10T07:00:00-05:00", "2026-11-10T12:00:00.000Z"),
"back-a-day": ("2026-11-11T01:00:00+07:00", "2026-11-10T18:00:00.000Z"),
"forward-a-day": ("2026-11-10T22:00:00-05:00", "2026-11-11T03:00:00.000Z"),
"year-end": ("2027-01-01T00:30:00+01:00", "2026-12-31T23:30:00.000Z"),
"leap-day": ("2024-02-29T23:00:00-02:00", "2024-03-01T01:00:00.000Z"),
"half-hour-offset": ("2026-11-10T17:30:00+05:30", "2026-11-10T12:00:00.000Z"),
"quarter-hour-offset": ("2026-11-10T17:45:00+05:45", "2026-11-10T12:00:00.000Z"),
"unknown-offset": ("2026-11-10T12:00:00-00:00", "2026-11-10T12:00:00.000Z"),
"fraction-one-digit": ("2026-11-10T12:00:00.5Z", "2026-11-10T12:00:00.500Z"),
"fraction-three-digits": (
"2026-11-10T12:00:00.123+01:00",
"2026-11-10T11:00:00.123Z",
),
"before-epoch": ("1970-01-01T00:30:00+01:00", "1969-12-31T23:30:00.000Z"),
"before-epoch-fraction": ("1969-12-31T23:59:59.999Z", "1969-12-31T23:59:59.999Z"),
"largest-offset": ("2026-11-10T00:00:00+14:00", "2026-11-09T10:00:00.000Z"),
"smallest-offset": ("2026-11-10T00:00:00-12:00", "2026-11-10T12:00:00.000Z"),
"lower-case": ("2026-11-10t12:00:00z", "2026-11-10T12:00:00.000Z"),
"year-one": ("0001-01-01T00:00:00Z", "0001-01-01T00:00:00.000Z"),
"year-9999": ("9999-12-31T23:59:59.999Z", "9999-12-31T23:59:59.999Z"),
}
# name: input that is not a valid RFC 3339 date-time
ERRORS = {
"no-offset": "2026-11-10T12:00:00",
"date-only": "2026-11-10",
"space-separator": "2026-11-10 12:00:00Z",
"no-seconds": "2026-11-10T12:00Z",
"offset-no-colon": "2026-11-10T12:00:00+0700",
"offset-hours-only": "2026-11-10T12:00:00+07",
"not-a-leap-year": "2026-02-29T12:00:00Z",
"april-31": "2026-04-31T12:00:00Z",
"month-13": "2026-13-01T12:00:00Z",
"day-zero": "2026-11-00T12:00:00Z",
"hour-24": "2026-11-10T24:00:00Z",
"minute-60": "2026-11-10T12:60:00Z",
"leap-second": "2016-12-31T23:59:60Z",
"offset-hour-24": "2026-11-10T12:00:00+24:00",
"offset-minute-60": "2026-11-10T12:00:00+07:60",
"comma-fraction": "2026-11-10T12:00:00,5Z",
"trailing-space": "2026-11-10T12:00:00Z ",
"empty": "",
}
@pytest.mark.parametrize(("timestamp", "want"), CASES.values(), ids=CASES.keys())
def test_to_utc(timestamp: str, want: str) -> None:
assert to_utc(timestamp) == want
@pytest.mark.parametrize("timestamp", ERRORS.values(), ids=ERRORS.keys())
def test_to_utc_rejects(timestamp: str) -> None:
with pytest.raises(ValueError):
to_utc(timestamp)
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-and-format-a-date/.
#include "to_utc.hpp"
#include <charconv>
#include <chrono>
#include <format>
#include <regex>
#include <string>
#include <string_view>
namespace {
// The date-time of RFC 3339 section 5.6, with a fraction of 1 to 3 digits.
// The groups: year, month, day, hour, minute, second, fraction, Z or offset,
// offset sign, offset hours, offset minutes.
const std::regex rfc3339(
"([0-9]{4})-([0-9]{2})-([0-9]{2})[Tt]([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])"
"(?:\\.([0-9]{1,3}))?([Zz]|([+-])([01][0-9]|2[0-3]):([0-5][0-9]))");
int number(const std::ssub_match& group) {
std::string_view digits(group.first, group.second);
int n = 0;
std::from_chars(digits.data(), digits.data() + digits.size(), n);
return n;
}
} // namespace
std::expected<std::string, std::string> to_utc(std::string_view timestamp) {
using namespace std::chrono;
std::string text(timestamp);
std::smatch m;
if (!std::regex_match(text, m, rfc3339)) {
return std::unexpected("not an RFC 3339 date-time: \"" + text + "\"");
}
// ok() is false for a date that is not in the calendar, as 2026-02-29.
year_month_day date{year{number(m[1])}, month{static_cast<unsigned>(number(m[2]))},
day{static_cast<unsigned>(number(m[3]))}};
if (!date.ok()) {
return std::unexpected("not a date in the calendar: \"" + text + "\"");
}
// The fraction: 1 to 3 digits, padded to milliseconds.
std::string fraction = m[7].str();
fraction.resize(3, '0');
sys_time<milliseconds> local = sys_days{date} + hours{number(m[4])} +
minutes{number(m[5])} + seconds{number(m[6])} +
milliseconds{std::stoi(fraction)};
// The offset is local time minus UTC. -00:00 is the same instant as Z.
minutes offset{0};
if (m[9].matched) {
offset = hours{number(m[10])} + minutes{number(m[11])};
if (m[9] == "-") {
offset = -offset;
}
}
// %F is %Y-%m-%d, and %T prints the seconds with the 3 digits of
// milliseconds.
return std::format("{:%FT%T}Z", local - offset);
}
to_utc.hpp 16 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-and-format-a-date/.
#ifndef TO_UTC_HPP
#define TO_UTC_HPP
#include <expected>
#include <string>
#include <string_view>
// to_utc returns the instant of an RFC 3339 timestamp in UTC, as
// YYYY-MM-DDTHH:MM:SS.sssZ, or an error message when timestamp is not an RFC
// 3339 date-time with an offset, or when its date is not in the calendar.
std::expected<std::string, std::string> to_utc(std::string_view timestamp);
#endif
test_to_utc.cpp 81 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-and-format-a-date/.
#include "to_utc.hpp"
#include <array>
#include <print>
#include <string_view>
namespace {
struct Case {
std::string_view name, timestamp, want;
};
struct Error {
std::string_view name, timestamp;
};
constexpr std::array<Case, 19> cases{{
{"utc", "2026-11-10T12:00:00Z", "2026-11-10T12:00:00.000Z"},
{"positive-offset", "2026-11-10T19:30:00+07:00", "2026-11-10T12:30:00.000Z"},
{"negative-offset", "2026-11-10T07:00:00-05:00", "2026-11-10T12:00:00.000Z"},
{"back-a-day", "2026-11-11T01:00:00+07:00", "2026-11-10T18:00:00.000Z"},
{"forward-a-day", "2026-11-10T22:00:00-05:00", "2026-11-11T03:00:00.000Z"},
{"year-end", "2027-01-01T00:30:00+01:00", "2026-12-31T23:30:00.000Z"},
{"leap-day", "2024-02-29T23:00:00-02:00", "2024-03-01T01:00:00.000Z"},
{"half-hour-offset", "2026-11-10T17:30:00+05:30", "2026-11-10T12:00:00.000Z"},
{"quarter-hour-offset", "2026-11-10T17:45:00+05:45", "2026-11-10T12:00:00.000Z"},
{"unknown-offset", "2026-11-10T12:00:00-00:00", "2026-11-10T12:00:00.000Z"},
{"fraction-one-digit", "2026-11-10T12:00:00.5Z", "2026-11-10T12:00:00.500Z"},
{"fraction-three-digits", "2026-11-10T12:00:00.123+01:00", "2026-11-10T11:00:00.123Z"},
{"before-epoch", "1970-01-01T00:30:00+01:00", "1969-12-31T23:30:00.000Z"},
{"before-epoch-fraction", "1969-12-31T23:59:59.999Z", "1969-12-31T23:59:59.999Z"},
{"largest-offset", "2026-11-10T00:00:00+14:00", "2026-11-09T10:00:00.000Z"},
{"smallest-offset", "2026-11-10T00:00:00-12:00", "2026-11-10T12:00:00.000Z"},
{"lower-case", "2026-11-10t12:00:00z", "2026-11-10T12:00:00.000Z"},
{"year-one", "0001-01-01T00:00:00Z", "0001-01-01T00:00:00.000Z"},
{"year-9999", "9999-12-31T23:59:59.999Z", "9999-12-31T23:59:59.999Z"},
}};
constexpr std::array<Error, 18> errors{{
{"no-offset", "2026-11-10T12:00:00"},
{"date-only", "2026-11-10"},
{"space-separator", "2026-11-10 12:00:00Z"},
{"no-seconds", "2026-11-10T12:00Z"},
{"offset-no-colon", "2026-11-10T12:00:00+0700"},
{"offset-hours-only", "2026-11-10T12:00:00+07"},
{"not-a-leap-year", "2026-02-29T12:00:00Z"},
{"april-31", "2026-04-31T12:00:00Z"},
{"month-13", "2026-13-01T12:00:00Z"},
{"day-zero", "2026-11-00T12:00:00Z"},
{"hour-24", "2026-11-10T24:00:00Z"},
{"minute-60", "2026-11-10T12:60:00Z"},
{"leap-second", "2016-12-31T23:59:60Z"},
{"offset-hour-24", "2026-11-10T12:00:00+24:00"},
{"offset-minute-60", "2026-11-10T12:00:00+07:60"},
{"comma-fraction", "2026-11-10T12:00:00,5Z"},
{"trailing-space", "2026-11-10T12:00:00Z "},
{"empty", ""},
}};
} // namespace
int main() {
int failures = 0;
for (const auto& [name, timestamp, want] : cases) {
auto got = to_utc(timestamp);
if (!got || *got != want) {
std::println(stderr, "case {}: got {}, want {}", name, got.value_or(got.error_or("")), want);
failures++;
}
}
for (const auto& [name, timestamp] : errors) {
if (auto got = to_utc(timestamp)) {
std::println(stderr, "case {}: got {}, want an error", name, *got);
failures++;
}
}
return failures > 0 ? 1 : 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-and-format-a-date/.
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Locale;
import java.util.regex.Pattern;
final class ToUtc {
// The date-time of RFC 3339 section 5.6, with a fraction of 1 to 3 digits.
// ISO_OFFSET_DATE_TIME accepts more than this (no seconds, the offset +07),
// so the pattern checks the syntax first.
private static final Pattern RFC3339 =
Pattern.compile(
"[0-9]{4}-[0-9]{2}-[0-9]{2}[Tt]([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]"
+ "(\\.[0-9]{1,3})?([Zz]|[+-]([01][0-9]|2[0-3]):[0-5][0-9])");
// "uuuu" is the year. "YYYY" is the week-based year, which is a different
// number in the last days of some years.
private static final DateTimeFormatter OUT =
DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ROOT);
private ToUtc() {}
/**
* Returns the instant of an RFC 3339 timestamp in UTC, as YYYY-MM-DDTHH:MM:SS.sssZ.
*
* @throws IllegalArgumentException when timestamp is not an RFC 3339 date-time with an offset,
* or when its date is not in the calendar
*/
static String toUtc(String timestamp) {
if (!RFC3339.matcher(timestamp).matches()) {
throw new IllegalArgumentException("not an RFC 3339 date-time: \"" + timestamp + "\"");
}
try {
// ISO_OFFSET_DATE_TIME uses ResolverStyle.STRICT, so 2026-02-29 is an error.
OffsetDateTime value =
OffsetDateTime.parse(
timestamp.toUpperCase(Locale.ROOT), DateTimeFormatter.ISO_OFFSET_DATE_TIME);
return value.withOffsetSameInstant(ZoneOffset.UTC).format(OUT);
} catch (DateTimeParseException e) {
throw new IllegalArgumentException("not a date in the calendar: \"" + timestamp + "\"", e);
}
}
}
ToUtcTest.java 69 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-and-format-a-date/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class ToUtcTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("utc", "2026-11-10T12:00:00Z", "2026-11-10T12:00:00.000Z"),
Arguments.of("positive-offset", "2026-11-10T19:30:00+07:00", "2026-11-10T12:30:00.000Z"),
Arguments.of("negative-offset", "2026-11-10T07:00:00-05:00", "2026-11-10T12:00:00.000Z"),
Arguments.of("back-a-day", "2026-11-11T01:00:00+07:00", "2026-11-10T18:00:00.000Z"),
Arguments.of("forward-a-day", "2026-11-10T22:00:00-05:00", "2026-11-11T03:00:00.000Z"),
Arguments.of("year-end", "2027-01-01T00:30:00+01:00", "2026-12-31T23:30:00.000Z"),
Arguments.of("leap-day", "2024-02-29T23:00:00-02:00", "2024-03-01T01:00:00.000Z"),
Arguments.of("half-hour-offset", "2026-11-10T17:30:00+05:30", "2026-11-10T12:00:00.000Z"),
Arguments.of("quarter-hour-offset", "2026-11-10T17:45:00+05:45", "2026-11-10T12:00:00.000Z"),
Arguments.of("unknown-offset", "2026-11-10T12:00:00-00:00", "2026-11-10T12:00:00.000Z"),
Arguments.of("fraction-one-digit", "2026-11-10T12:00:00.5Z", "2026-11-10T12:00:00.500Z"),
Arguments.of("fraction-three-digits", "2026-11-10T12:00:00.123+01:00", "2026-11-10T11:00:00.123Z"),
Arguments.of("before-epoch", "1970-01-01T00:30:00+01:00", "1969-12-31T23:30:00.000Z"),
Arguments.of("before-epoch-fraction", "1969-12-31T23:59:59.999Z", "1969-12-31T23:59:59.999Z"),
Arguments.of("largest-offset", "2026-11-10T00:00:00+14:00", "2026-11-09T10:00:00.000Z"),
Arguments.of("smallest-offset", "2026-11-10T00:00:00-12:00", "2026-11-10T12:00:00.000Z"),
Arguments.of("lower-case", "2026-11-10t12:00:00z", "2026-11-10T12:00:00.000Z"),
Arguments.of("year-one", "0001-01-01T00:00:00Z", "0001-01-01T00:00:00.000Z"),
Arguments.of("year-9999", "9999-12-31T23:59:59.999Z", "9999-12-31T23:59:59.999Z"));
}
static Stream<Arguments> errors() {
return Stream.of(
Arguments.of("no-offset", "2026-11-10T12:00:00"),
Arguments.of("date-only", "2026-11-10"),
Arguments.of("space-separator", "2026-11-10 12:00:00Z"),
Arguments.of("no-seconds", "2026-11-10T12:00Z"),
Arguments.of("offset-no-colon", "2026-11-10T12:00:00+0700"),
Arguments.of("offset-hours-only", "2026-11-10T12:00:00+07"),
Arguments.of("not-a-leap-year", "2026-02-29T12:00:00Z"),
Arguments.of("april-31", "2026-04-31T12:00:00Z"),
Arguments.of("month-13", "2026-13-01T12:00:00Z"),
Arguments.of("day-zero", "2026-11-00T12:00:00Z"),
Arguments.of("hour-24", "2026-11-10T24:00:00Z"),
Arguments.of("minute-60", "2026-11-10T12:60:00Z"),
Arguments.of("leap-second", "2016-12-31T23:59:60Z"),
Arguments.of("offset-hour-24", "2026-11-10T12:00:00+24:00"),
Arguments.of("offset-minute-60", "2026-11-10T12:00:00+07:60"),
Arguments.of("comma-fraction", "2026-11-10T12:00:00,5Z"),
Arguments.of("trailing-space", "2026-11-10T12:00:00Z "),
Arguments.of("empty", ""));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void convertsToUtc(String name, String timestamp, String want) {
assertEquals(want, ToUtc.toUtc(timestamp));
}
@ParameterizedTest(name = "{0}")
@MethodSource("errors")
void rejectsInvalidInput(String name, String timestamp) {
assertThrows(IllegalArgumentException.class, () -> ToUtc.toUtc(timestamp));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-and-format-a-date/.
#include "to_utc.h"
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
// number reads len digits from s into *n. It returns false when one of them
// is not one of the ASCII digits 0 to 9.
static bool number(const char *s, int len, long long *n) {
*n = 0;
for (int i = 0; i < len; i++) {
if (s[i] < '0' || s[i] > '9') {
return false;
}
*n = *n * 10 + (s[i] - '0');
}
return true;
}
static long long days_in_month(long long year, long long month) {
static const long long days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
bool leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
return month == 2 && leap ? 29 : days[month - 1];
}
// floor_div is division that rounds down. The operator / rounds toward zero.
static long long floor_div(long long a, long long b) {
return a / b - (a % b != 0 && (a < 0) != (b < 0));
}
// days_from_civil returns the days from 1970-01-01 to the date (Howard
// Hinnant). A year starts on 1 March here, so the leap day is the last day.
static long long days_from_civil(long long y, long long m, long long d) {
y -= m <= 2;
long long era = floor_div(y, 400);
long long yoe = y - era * 400;
long long doy = (153 * (m > 2 ? m - 3 : m + 9) + 2) / 5 + d - 1;
long long doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
return era * 146097 + doe - 719468;
}
// civil_from_days is the inverse of days_from_civil.
static void civil_from_days(long long z, long long *y, long long *m, long long *d) {
z += 719468;
long long era = floor_div(z, 146097);
long long doe = z - era * 146097;
long long yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
long long doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
long long mp = (5 * doy + 2) / 153;
*d = doy - (153 * mp + 2) / 5 + 1;
*m = mp < 10 ? mp + 3 : mp - 9;
*y = yoe + era * 400 + (*m <= 2);
}
int to_utc(const char *timestamp, char *out, size_t size) {
const char *s = timestamp;
size_t n = strlen(s);
long long year, month, day, hour, minute, second;
// YYYY-MM-DDTHH:MM:SS is 19 characters.
if (n < 20 || !number(s, 4, &year) || s[4] != '-' || !number(s + 5, 2, &month) ||
s[7] != '-' || !number(s + 8, 2, &day) || (s[10] != 'T' && s[10] != 't') ||
!number(s + 11, 2, &hour) || s[13] != ':' || !number(s + 14, 2, &minute) ||
s[16] != ':' || !number(s + 17, 2, &second)) {
return -1;
}
if (month < 1 || month > 12 || day < 1 || day > days_in_month(year, month) || hour > 23 ||
minute > 59 || second > 59) {
return -1;
}
// The fraction: a dot and 1 to 3 digits, padded to milliseconds.
size_t i = 19;
long long ms = 0;
if (s[i] == '.') {
size_t start = ++i;
while (i - start < 3 && s[i] >= '0' && s[i] <= '9') {
ms = ms * 10 + (s[i++] - '0');
}
if (i == start) {
return -1;
}
for (size_t k = i - start; k < 3; k++) {
ms *= 10;
}
}
// The offset: Z, or a sign, HH:MM. -00:00 is the same instant as Z.
long long offset = 0;
if ((s[i] == 'Z' || s[i] == 'z') && i + 1 == n) {
offset = 0;
} else if ((s[i] == '+' || s[i] == '-') && i + 6 == n && s[i + 3] == ':') {
long long oh, om;
if (!number(s + i + 1, 2, &oh) || !number(s + i + 4, 2, &om) || oh > 23 || om > 59) {
return -1;
}
offset = (oh * 3600 + om * 60) * (s[i] == '+' ? 1 : -1);
} else {
return -1;
}
long long seconds =
days_from_civil(year, month, day) * 86400 + hour * 3600 + minute * 60 + second - offset;
long long total = seconds * 1000 + ms;
long long days = floor_div(total, 86400000);
long long rest = total - days * 86400000;
long long y, m, d;
civil_from_days(days, &y, &m, &d);
// %04lld pads the year to 4 digits, as date-fullyear in RFC 3339 needs.
snprintf(out, size, "%04lld-%02lld-%02lldT%02lld:%02lld:%02lld.%03lldZ", y, m, d,
rest / 3600000, rest / 60000 % 60, rest / 1000 % 60, rest % 1000);
return 0;
}
to_utc.h 19 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-and-format-a-date/.
#ifndef TO_UTC_H
#define TO_UTC_H
#include <stddef.h>
// TO_UTC_SIZE is the size of the result: YYYY-MM-DDTHH:MM:SS.sssZ and a NUL.
#define TO_UTC_SIZE 25
// to_utc writes the instant of the RFC 3339 timestamp in UTC to out, as
// YYYY-MM-DDTHH:MM:SS.sssZ, and returns 0. It returns -1 and does not write
// to out when timestamp is not an RFC 3339 date-time with an offset, or when
// its date is not in the calendar. size is the size of out; it must be at
// least TO_UTC_SIZE.
int to_utc(const char *timestamp, char *out, size_t size);
#endif
test_to_utc.c 67 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-and-format-a-date/.
#include "to_utc.h"
#include <stdio.h>
#include <string.h>
static int failures = 0;
// check compares to_utc(timestamp) with want. A NULL want means an error.
static void check(const char *name, const char *timestamp, const char *want) {
char got[TO_UTC_SIZE] = "";
int status = to_utc(timestamp, got, sizeof got);
if (want == NULL && status != -1) {
fprintf(stderr, "case %s: got \"%s\", want an error\n", name, got);
failures++;
} else if (want != NULL && (status != 0 || strcmp(got, want) != 0)) {
fprintf(stderr, "case %s: got %d \"%s\", want \"%s\"\n", name, status, got, want);
failures++;
}
}
int main(void) {
check("utc", "2026-11-10T12:00:00Z", "2026-11-10T12:00:00.000Z");
check("positive-offset", "2026-11-10T19:30:00+07:00", "2026-11-10T12:30:00.000Z");
check("negative-offset", "2026-11-10T07:00:00-05:00", "2026-11-10T12:00:00.000Z");
check("back-a-day", "2026-11-11T01:00:00+07:00", "2026-11-10T18:00:00.000Z");
check("forward-a-day", "2026-11-10T22:00:00-05:00", "2026-11-11T03:00:00.000Z");
check("year-end", "2027-01-01T00:30:00+01:00", "2026-12-31T23:30:00.000Z");
check("leap-day", "2024-02-29T23:00:00-02:00", "2024-03-01T01:00:00.000Z");
check("half-hour-offset", "2026-11-10T17:30:00+05:30", "2026-11-10T12:00:00.000Z");
check("quarter-hour-offset", "2026-11-10T17:45:00+05:45", "2026-11-10T12:00:00.000Z");
check("unknown-offset", "2026-11-10T12:00:00-00:00", "2026-11-10T12:00:00.000Z");
check("fraction-one-digit", "2026-11-10T12:00:00.5Z", "2026-11-10T12:00:00.500Z");
check("fraction-three-digits", "2026-11-10T12:00:00.123+01:00", "2026-11-10T11:00:00.123Z");
check("before-epoch", "1970-01-01T00:30:00+01:00", "1969-12-31T23:30:00.000Z");
check("before-epoch-fraction", "1969-12-31T23:59:59.999Z", "1969-12-31T23:59:59.999Z");
check("largest-offset", "2026-11-10T00:00:00+14:00", "2026-11-09T10:00:00.000Z");
check("smallest-offset", "2026-11-10T00:00:00-12:00", "2026-11-10T12:00:00.000Z");
check("lower-case", "2026-11-10t12:00:00z", "2026-11-10T12:00:00.000Z");
check("year-one", "0001-01-01T00:00:00Z", "0001-01-01T00:00:00.000Z");
check("year-9999", "9999-12-31T23:59:59.999Z", "9999-12-31T23:59:59.999Z");
check("no-offset", "2026-11-10T12:00:00", NULL);
check("date-only", "2026-11-10", NULL);
check("space-separator", "2026-11-10 12:00:00Z", NULL);
check("no-seconds", "2026-11-10T12:00Z", NULL);
check("offset-no-colon", "2026-11-10T12:00:00+0700", NULL);
check("offset-hours-only", "2026-11-10T12:00:00+07", NULL);
check("not-a-leap-year", "2026-02-29T12:00:00Z", NULL);
check("april-31", "2026-04-31T12:00:00Z", NULL);
check("month-13", "2026-13-01T12:00:00Z", NULL);
check("day-zero", "2026-11-00T12:00:00Z", NULL);
check("hour-24", "2026-11-10T24:00:00Z", NULL);
check("minute-60", "2026-11-10T12:60:00Z", NULL);
check("leap-second", "2016-12-31T23:59:60Z", NULL);
check("offset-hour-24", "2026-11-10T12:00:00+24:00", NULL);
check("offset-minute-60", "2026-11-10T12:00:00+07:60", NULL);
check("comma-fraction", "2026-11-10T12:00:00,5Z", NULL);
check("trailing-space", "2026-11-10T12:00:00Z ", NULL);
check("empty", "", NULL);
if (failures > 0) {
fprintf(stderr, "%d failures\n", failures);
return 1;
}
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-and-format-a-date/.
using System.Globalization;
using System.Text.RegularExpressions;
public static partial class Timestamp
{
// The date-time of RFC 3339 section 5.6, with a fraction of 1 to 3 digits.
// The format "zzz" also accepts +0700, so the pattern checks the syntax
// first. [0-9] is ASCII only; \d also matches other digits. \z is the end
// of the text; $ also matches before a final line end.
[GeneratedRegex(@"^[0-9]{4}-[0-9]{2}-[0-9]{2}[Tt]([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\.[0-9]{1,3})?([Zz]|[+-]([01][0-9]|2[0-3]):[0-5][0-9])\z")]
private static partial Regex Rfc3339();
// "FFF" is 0 to 3 fraction digits. "MM" is the month and "mm" is the minute.
private static readonly string[] Formats =
[
"yyyy-MM-dd'T'HH:mm:ss.FFFzzz",
"yyyy-MM-dd'T'HH:mm:ss.FFF'Z'",
];
/// <summary>
/// Returns the instant of an RFC 3339 timestamp in UTC, as YYYY-MM-DDTHH:MM:SS.sssZ.
/// </summary>
/// <exception cref="FormatException">
/// timestamp is not an RFC 3339 date-time with an offset, or its date is not in the calendar.
/// </exception>
public static string ToUtc(string timestamp)
{
if (!Rfc3339().IsMatch(timestamp))
{
throw new FormatException($"not an RFC 3339 date-time: \"{timestamp}\"");
}
// The second format has no offset specifier. AssumeUniversal gives it
// the offset +00:00; with no style, the parser uses the offset of the
// local time zone.
DateTimeOffset value = DateTimeOffset.ParseExact(
timestamp.ToUpperInvariant(),
Formats,
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal);
return value.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss.fff'Z'", CultureInfo.InvariantCulture);
}
}
TimestampTests.cs 68 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-and-format-a-date/.
using Xunit;
public sealed class TimestampTests
{
public static TheoryData<string, string, string> Cases => new()
{
{ "utc", "2026-11-10T12:00:00Z", "2026-11-10T12:00:00.000Z" },
{ "positive-offset", "2026-11-10T19:30:00+07:00", "2026-11-10T12:30:00.000Z" },
{ "negative-offset", "2026-11-10T07:00:00-05:00", "2026-11-10T12:00:00.000Z" },
{ "back-a-day", "2026-11-11T01:00:00+07:00", "2026-11-10T18:00:00.000Z" },
{ "forward-a-day", "2026-11-10T22:00:00-05:00", "2026-11-11T03:00:00.000Z" },
{ "year-end", "2027-01-01T00:30:00+01:00", "2026-12-31T23:30:00.000Z" },
{ "leap-day", "2024-02-29T23:00:00-02:00", "2024-03-01T01:00:00.000Z" },
{ "half-hour-offset", "2026-11-10T17:30:00+05:30", "2026-11-10T12:00:00.000Z" },
{ "quarter-hour-offset", "2026-11-10T17:45:00+05:45", "2026-11-10T12:00:00.000Z" },
{ "unknown-offset", "2026-11-10T12:00:00-00:00", "2026-11-10T12:00:00.000Z" },
{ "fraction-one-digit", "2026-11-10T12:00:00.5Z", "2026-11-10T12:00:00.500Z" },
{ "fraction-three-digits", "2026-11-10T12:00:00.123+01:00", "2026-11-10T11:00:00.123Z" },
{ "before-epoch", "1970-01-01T00:30:00+01:00", "1969-12-31T23:30:00.000Z" },
{ "before-epoch-fraction", "1969-12-31T23:59:59.999Z", "1969-12-31T23:59:59.999Z" },
{ "largest-offset", "2026-11-10T00:00:00+14:00", "2026-11-09T10:00:00.000Z" },
{ "smallest-offset", "2026-11-10T00:00:00-12:00", "2026-11-10T12:00:00.000Z" },
{ "lower-case", "2026-11-10t12:00:00z", "2026-11-10T12:00:00.000Z" },
{ "year-one", "0001-01-01T00:00:00Z", "0001-01-01T00:00:00.000Z" },
{ "year-9999", "9999-12-31T23:59:59.999Z", "9999-12-31T23:59:59.999Z" },
};
public static TheoryData<string, string> Errors => new()
{
{ "no-offset", "2026-11-10T12:00:00" },
{ "date-only", "2026-11-10" },
{ "space-separator", "2026-11-10 12:00:00Z" },
{ "no-seconds", "2026-11-10T12:00Z" },
{ "offset-no-colon", "2026-11-10T12:00:00+0700" },
{ "offset-hours-only", "2026-11-10T12:00:00+07" },
{ "not-a-leap-year", "2026-02-29T12:00:00Z" },
{ "april-31", "2026-04-31T12:00:00Z" },
{ "month-13", "2026-13-01T12:00:00Z" },
{ "day-zero", "2026-11-00T12:00:00Z" },
{ "hour-24", "2026-11-10T24:00:00Z" },
{ "minute-60", "2026-11-10T12:60:00Z" },
{ "leap-second", "2016-12-31T23:59:60Z" },
{ "offset-hour-24", "2026-11-10T12:00:00+24:00" },
{ "offset-minute-60", "2026-11-10T12:00:00+07:60" },
{ "comma-fraction", "2026-11-10T12:00:00,5Z" },
{ "trailing-space", "2026-11-10T12:00:00Z " },
{ "empty", "" },
};
[Theory]
[MemberData(nameof(Cases))]
public void ConvertsToUtc(string name, string timestamp, string want)
{
string got = Timestamp.ToUtc(timestamp);
Assert.True(got == want, $"{name}: got {got}, want {want}");
}
[Theory]
[MemberData(nameof(Errors))]
public void RejectsInvalidInput(string name, string timestamp)
{
Exception? error = Record.Exception(() => Timestamp.ToUtc(timestamp));
Assert.True(error is FormatException, $"{name}: got {error?.GetType().Name ?? "no exception"}");
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-and-format-a-date/.
// The date-time of RFC 3339 section 5.6, with a fraction of 1 to 3 digits.
// Date accepts more than this, and it rolls an invalid day over into the next
// month, so the pattern checks the syntax and daysInMonth checks the day.
const RFC3339 =
/^(\d{4})-(\d{2})-(\d{2})[Tt]([01]\d|2[0-3]):[0-5]\d:[0-5]\d(\.\d{1,3})?([Zz]|[+-]([01]\d|2[0-3]):[0-5]\d)$/;
function daysInMonth(year, month) {
const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
return [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1];
}
// Returns the instant of an RFC 3339 timestamp in UTC, as YYYY-MM-DDTHH:MM:SS.sssZ.
// Throws RangeError when timestamp is not an RFC 3339 date-time with an offset,
// or when its date is not in the calendar.
export function toUtc(timestamp) {
const match = RFC3339.exec(timestamp);
if (match === null) {
throw new RangeError(`not an RFC 3339 date-time: ${JSON.stringify(timestamp)}`);
}
const year = Number(match[1]);
const month = Number(match[2]);
const day = Number(match[3]);
if (month < 1 || month > 12 || day < 1 || day > daysInMonth(year, month)) {
throw new RangeError(`not a date in the calendar: ${JSON.stringify(timestamp)}`);
}
// The pattern makes sure that there is an offset, so the time zone of the
// machine has no effect.
return new Date(timestamp.toUpperCase()).toISOString();
}
toUtc.test.js 64 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-and-format-a-date/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { toUtc } from "./toUtc.js";
// [case, input, expected value]
const cases = [
["utc", "2026-11-10T12:00:00Z", "2026-11-10T12:00:00.000Z"],
["positive-offset", "2026-11-10T19:30:00+07:00", "2026-11-10T12:30:00.000Z"],
["negative-offset", "2026-11-10T07:00:00-05:00", "2026-11-10T12:00:00.000Z"],
["back-a-day", "2026-11-11T01:00:00+07:00", "2026-11-10T18:00:00.000Z"],
["forward-a-day", "2026-11-10T22:00:00-05:00", "2026-11-11T03:00:00.000Z"],
["year-end", "2027-01-01T00:30:00+01:00", "2026-12-31T23:30:00.000Z"],
["leap-day", "2024-02-29T23:00:00-02:00", "2024-03-01T01:00:00.000Z"],
["half-hour-offset", "2026-11-10T17:30:00+05:30", "2026-11-10T12:00:00.000Z"],
["quarter-hour-offset", "2026-11-10T17:45:00+05:45", "2026-11-10T12:00:00.000Z"],
["unknown-offset", "2026-11-10T12:00:00-00:00", "2026-11-10T12:00:00.000Z"],
["fraction-one-digit", "2026-11-10T12:00:00.5Z", "2026-11-10T12:00:00.500Z"],
["fraction-three-digits", "2026-11-10T12:00:00.123+01:00", "2026-11-10T11:00:00.123Z"],
["before-epoch", "1970-01-01T00:30:00+01:00", "1969-12-31T23:30:00.000Z"],
["before-epoch-fraction", "1969-12-31T23:59:59.999Z", "1969-12-31T23:59:59.999Z"],
["largest-offset", "2026-11-10T00:00:00+14:00", "2026-11-09T10:00:00.000Z"],
["smallest-offset", "2026-11-10T00:00:00-12:00", "2026-11-10T12:00:00.000Z"],
["lower-case", "2026-11-10t12:00:00z", "2026-11-10T12:00:00.000Z"],
["year-one", "0001-01-01T00:00:00Z", "0001-01-01T00:00:00.000Z"],
["year-9999", "9999-12-31T23:59:59.999Z", "9999-12-31T23:59:59.999Z"],
];
// [case, input that is not a valid RFC 3339 date-time]
const errors = [
["no-offset", "2026-11-10T12:00:00"],
["date-only", "2026-11-10"],
["space-separator", "2026-11-10 12:00:00Z"],
["no-seconds", "2026-11-10T12:00Z"],
["offset-no-colon", "2026-11-10T12:00:00+0700"],
["offset-hours-only", "2026-11-10T12:00:00+07"],
["not-a-leap-year", "2026-02-29T12:00:00Z"],
["april-31", "2026-04-31T12:00:00Z"],
["month-13", "2026-13-01T12:00:00Z"],
["day-zero", "2026-11-00T12:00:00Z"],
["hour-24", "2026-11-10T24:00:00Z"],
["minute-60", "2026-11-10T12:60:00Z"],
["leap-second", "2016-12-31T23:59:60Z"],
["offset-hour-24", "2026-11-10T12:00:00+24:00"],
["offset-minute-60", "2026-11-10T12:00:00+07:60"],
["comma-fraction", "2026-11-10T12:00:00,5Z"],
["trailing-space", "2026-11-10T12:00:00Z "],
["empty", ""],
];
for (const [name, timestamp, want] of cases) {
test(name, () => {
assert.equal(toUtc(timestamp), want);
});
}
for (const [name, timestamp] of errors) {
test(name, () => {
assert.throws(() => toUtc(timestamp), RangeError);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-and-format-a-date/.
// The date-time of RFC 3339 section 5.6, with a fraction of 1 to 3 digits.
// Date accepts more than this, and it rolls an invalid day over into the next
// month, so the pattern checks the syntax and daysInMonth checks the day.
const RFC3339 =
/^(\d{4})-(\d{2})-(\d{2})[Tt]([01]\d|2[0-3]):[0-5]\d:[0-5]\d(\.\d{1,3})?([Zz]|[+-]([01]\d|2[0-3]):[0-5]\d)$/;
function daysInMonth(year: number, month: number): number {
const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
return [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1]!;
}
// Returns the instant of an RFC 3339 timestamp in UTC, as YYYY-MM-DDTHH:MM:SS.sssZ.
// Throws RangeError when timestamp is not an RFC 3339 date-time with an offset,
// or when its date is not in the calendar.
export function toUtc(timestamp: string): string {
const match = RFC3339.exec(timestamp);
if (match === null) {
throw new RangeError(`not an RFC 3339 date-time: ${JSON.stringify(timestamp)}`);
}
const year = Number(match[1]);
const month = Number(match[2]);
const day = Number(match[3]);
if (month < 1 || month > 12 || day < 1 || day > daysInMonth(year, month)) {
throw new RangeError(`not a date in the calendar: ${JSON.stringify(timestamp)}`);
}
// The pattern makes sure that there is an offset, so the time zone of the
// machine has no effect.
return new Date(timestamp.toUpperCase()).toISOString();
}
toUtc.test.ts 64 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-and-format-a-date/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { toUtc } from "./toUtc.ts";
// [case, input, expected value]
const cases = [
["utc", "2026-11-10T12:00:00Z", "2026-11-10T12:00:00.000Z"],
["positive-offset", "2026-11-10T19:30:00+07:00", "2026-11-10T12:30:00.000Z"],
["negative-offset", "2026-11-10T07:00:00-05:00", "2026-11-10T12:00:00.000Z"],
["back-a-day", "2026-11-11T01:00:00+07:00", "2026-11-10T18:00:00.000Z"],
["forward-a-day", "2026-11-10T22:00:00-05:00", "2026-11-11T03:00:00.000Z"],
["year-end", "2027-01-01T00:30:00+01:00", "2026-12-31T23:30:00.000Z"],
["leap-day", "2024-02-29T23:00:00-02:00", "2024-03-01T01:00:00.000Z"],
["half-hour-offset", "2026-11-10T17:30:00+05:30", "2026-11-10T12:00:00.000Z"],
["quarter-hour-offset", "2026-11-10T17:45:00+05:45", "2026-11-10T12:00:00.000Z"],
["unknown-offset", "2026-11-10T12:00:00-00:00", "2026-11-10T12:00:00.000Z"],
["fraction-one-digit", "2026-11-10T12:00:00.5Z", "2026-11-10T12:00:00.500Z"],
["fraction-three-digits", "2026-11-10T12:00:00.123+01:00", "2026-11-10T11:00:00.123Z"],
["before-epoch", "1970-01-01T00:30:00+01:00", "1969-12-31T23:30:00.000Z"],
["before-epoch-fraction", "1969-12-31T23:59:59.999Z", "1969-12-31T23:59:59.999Z"],
["largest-offset", "2026-11-10T00:00:00+14:00", "2026-11-09T10:00:00.000Z"],
["smallest-offset", "2026-11-10T00:00:00-12:00", "2026-11-10T12:00:00.000Z"],
["lower-case", "2026-11-10t12:00:00z", "2026-11-10T12:00:00.000Z"],
["year-one", "0001-01-01T00:00:00Z", "0001-01-01T00:00:00.000Z"],
["year-9999", "9999-12-31T23:59:59.999Z", "9999-12-31T23:59:59.999Z"],
];
// [case, input that is not a valid RFC 3339 date-time]
const errors = [
["no-offset", "2026-11-10T12:00:00"],
["date-only", "2026-11-10"],
["space-separator", "2026-11-10 12:00:00Z"],
["no-seconds", "2026-11-10T12:00Z"],
["offset-no-colon", "2026-11-10T12:00:00+0700"],
["offset-hours-only", "2026-11-10T12:00:00+07"],
["not-a-leap-year", "2026-02-29T12:00:00Z"],
["april-31", "2026-04-31T12:00:00Z"],
["month-13", "2026-13-01T12:00:00Z"],
["day-zero", "2026-11-00T12:00:00Z"],
["hour-24", "2026-11-10T24:00:00Z"],
["minute-60", "2026-11-10T12:60:00Z"],
["leap-second", "2016-12-31T23:59:60Z"],
["offset-hour-24", "2026-11-10T12:00:00+24:00"],
["offset-minute-60", "2026-11-10T12:00:00+07:60"],
["comma-fraction", "2026-11-10T12:00:00,5Z"],
["trailing-space", "2026-11-10T12:00:00Z "],
["empty", ""],
];
for (const [name, timestamp, want] of cases) {
test(name, () => {
assert.equal(toUtc(timestamp), want);
});
}
for (const [name, timestamp] of errors) {
test(name, () => {
assert.throws(() => toUtc(timestamp), RangeError);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-and-format-a-date/.
package toutc
import (
"fmt"
"regexp"
"strings"
"time"
)
// rfc3339 is the date-time of RFC 3339 section 5.6, with a fraction of 1 to 3
// digits. time.Parse with time.RFC3339 accepts more than this (a comma before
// the fraction, the offsets +24:00 and +07:60), so the pattern checks the
// syntax first.
var rfc3339 = regexp.MustCompile(`^[0-9]{4}-[0-9]{2}-[0-9]{2}[Tt]([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\.[0-9]{1,3})?([Zz]|[+-]([01][0-9]|2[0-3]):[0-5][0-9])$`)
// ToUTC returns the instant of an RFC 3339 timestamp in UTC, as
// YYYY-MM-DDTHH:MM:SS.sssZ. It returns an error when timestamp is not an RFC
// 3339 date-time with an offset, or when its date is not in the calendar.
func ToUTC(timestamp string) (string, error) {
if !rfc3339.MatchString(timestamp) {
return "", fmt.Errorf("not an RFC 3339 date-time: %q", timestamp)
}
// time.Parse rejects 2026-02-29 with "day out of range".
t, err := time.Parse(time.RFC3339, strings.ToUpper(timestamp))
if err != nil {
return "", err
}
// A layout is the reference time Mon Jan 2 15:04:05 MST 2006, written in
// the form to print. "Z07:00" prints Z for UTC.
return t.UTC().Format("2006-01-02T15:04:05.000Z07:00"), nil
}
to_utc_test.go 68 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-and-format-a-date/.
package toutc
import "testing"
func TestToUTC(t *testing.T) {
cases := []struct{ name, timestamp, want string }{
{"utc", "2026-11-10T12:00:00Z", "2026-11-10T12:00:00.000Z"},
{"positive-offset", "2026-11-10T19:30:00+07:00", "2026-11-10T12:30:00.000Z"},
{"negative-offset", "2026-11-10T07:00:00-05:00", "2026-11-10T12:00:00.000Z"},
{"back-a-day", "2026-11-11T01:00:00+07:00", "2026-11-10T18:00:00.000Z"},
{"forward-a-day", "2026-11-10T22:00:00-05:00", "2026-11-11T03:00:00.000Z"},
{"year-end", "2027-01-01T00:30:00+01:00", "2026-12-31T23:30:00.000Z"},
{"leap-day", "2024-02-29T23:00:00-02:00", "2024-03-01T01:00:00.000Z"},
{"half-hour-offset", "2026-11-10T17:30:00+05:30", "2026-11-10T12:00:00.000Z"},
{"quarter-hour-offset", "2026-11-10T17:45:00+05:45", "2026-11-10T12:00:00.000Z"},
{"unknown-offset", "2026-11-10T12:00:00-00:00", "2026-11-10T12:00:00.000Z"},
{"fraction-one-digit", "2026-11-10T12:00:00.5Z", "2026-11-10T12:00:00.500Z"},
{"fraction-three-digits", "2026-11-10T12:00:00.123+01:00", "2026-11-10T11:00:00.123Z"},
{"before-epoch", "1970-01-01T00:30:00+01:00", "1969-12-31T23:30:00.000Z"},
{"before-epoch-fraction", "1969-12-31T23:59:59.999Z", "1969-12-31T23:59:59.999Z"},
{"largest-offset", "2026-11-10T00:00:00+14:00", "2026-11-09T10:00:00.000Z"},
{"smallest-offset", "2026-11-10T00:00:00-12:00", "2026-11-10T12:00:00.000Z"},
{"lower-case", "2026-11-10t12:00:00z", "2026-11-10T12:00:00.000Z"},
{"year-one", "0001-01-01T00:00:00Z", "0001-01-01T00:00:00.000Z"},
{"year-9999", "9999-12-31T23:59:59.999Z", "9999-12-31T23:59:59.999Z"},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
got, err := ToUTC(c.timestamp)
if err != nil || got != c.want {
t.Errorf("ToUTC(%q) = %q, %v; want %q, nil", c.timestamp, got, err, c.want)
}
})
}
}
func TestToUTCRejects(t *testing.T) {
errors := []struct{ name, timestamp string }{
{"no-offset", "2026-11-10T12:00:00"},
{"date-only", "2026-11-10"},
{"space-separator", "2026-11-10 12:00:00Z"},
{"no-seconds", "2026-11-10T12:00Z"},
{"offset-no-colon", "2026-11-10T12:00:00+0700"},
{"offset-hours-only", "2026-11-10T12:00:00+07"},
{"not-a-leap-year", "2026-02-29T12:00:00Z"},
{"april-31", "2026-04-31T12:00:00Z"},
{"month-13", "2026-13-01T12:00:00Z"},
{"day-zero", "2026-11-00T12:00:00Z"},
{"hour-24", "2026-11-10T24:00:00Z"},
{"minute-60", "2026-11-10T12:60:00Z"},
{"leap-second", "2016-12-31T23:59:60Z"},
{"offset-hour-24", "2026-11-10T12:00:00+24:00"},
{"offset-minute-60", "2026-11-10T12:00:00+07:60"},
{"comma-fraction", "2026-11-10T12:00:00,5Z"},
{"trailing-space", "2026-11-10T12:00:00Z "},
{"empty", ""},
}
for _, c := range errors {
t.Run(c.name, func(t *testing.T) {
if got, err := ToUTC(c.timestamp); err == nil {
t.Errorf("ToUTC(%q) = %q, nil; want an error", c.timestamp, got)
}
})
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-and-format-a-date/.
//! The Rust standard library has no calendar: std::time measures durations
//! and instants, but it has no years, months or days. So this crate parses the
//! text by hand and counts days with the algorithms of Howard Hinnant.
use std::error::Error;
use std::fmt;
/// The error of [`to_utc`]: the text is not an RFC 3339 date-time with an
/// offset, or its date is not in the calendar.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseError {
input: String,
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "not an RFC 3339 date-time: {:?}", self.input)
}
}
impl Error for ParseError {}
/// Returns the instant of an RFC 3339 timestamp in UTC, as
/// YYYY-MM-DDTHH:MM:SS.sssZ. The fraction can have 1 to 3 digits.
pub fn to_utc(timestamp: &str) -> Result<String, ParseError> {
let millis = parse(timestamp.as_bytes()).ok_or_else(|| ParseError {
input: timestamp.to_string(),
})?;
let days = millis.div_euclid(86_400_000);
let ms = millis.rem_euclid(86_400_000);
let (year, month, day) = civil_from_days(days);
Ok(format!(
"{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{:03}Z",
ms / 3_600_000,
ms / 60_000 % 60,
ms / 1000 % 60,
ms % 1000
))
}
/// Returns the milliseconds from 1970-01-01T00:00:00Z, or None when the text
/// is not valid.
fn parse(b: &[u8]) -> Option<i64> {
let year = number(b, 0, 4)?;
let month = number(b, 5, 2)?;
let day = number(b, 8, 2)?;
let hour = number(b, 11, 2)?;
let minute = number(b, 14, 2)?;
let second = number(b, 17, 2)?;
if b[4] != b'-'
|| b[7] != b'-'
|| !matches!(b[10], b'T' | b't')
|| b[13] != b':'
|| b[16] != b':'
{
return None;
}
if !(1..=12).contains(&month) || day < 1 || day > days_in_month(year, month) {
return None;
}
if hour > 23 || minute > 59 || second > 59 {
return None;
}
// The fraction: a dot and 1 to 3 digits, padded to milliseconds.
let mut i = 19;
let mut ms = 0;
if b.get(i) == Some(&b'.') {
i += 1;
let start = i;
while i < b.len() && b[i].is_ascii_digit() && i - start < 3 {
ms = ms * 10 + i64::from(b[i] - b'0');
i += 1;
}
let digits = i - start;
if digits == 0 {
return None;
}
ms *= 10_i64.pow(3 - digits as u32);
}
// The offset: Z, or a sign, two digits of hours, a colon and two digits of
// minutes. -00:00 is the same instant as Z (RFC 3339 section 4.3).
let offset = match b.get(i)? {
b'Z' | b'z' if i + 1 == b.len() => 0,
&sign @ (b'+' | b'-') if i + 6 == b.len() && b[i + 3] == b':' => {
let hours = number(b, i + 1, 2)?;
let minutes = number(b, i + 4, 2)?;
if hours > 23 || minutes > 59 {
return None;
}
let seconds = hours * 3600 + minutes * 60;
if sign == b'+' { seconds } else { -seconds }
}
_ => return None,
};
let seconds = days_from_civil(year, month, day) * 86_400 + hour * 3600 + minute * 60 + second;
Some((seconds - offset) * 1000 + ms)
}
/// Returns the number made of the ASCII digits b[start..start + len], or None.
fn number(b: &[u8], start: usize, len: usize) -> Option<i64> {
let digits = b.get(start..start + len)?;
digits.iter().try_fold(0, |n, &c| {
c.is_ascii_digit().then(|| n * 10 + i64::from(c - b'0'))
})
}
fn days_in_month(year: i64, month: i64) -> i64 {
let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
match month {
2 if leap => 29,
2 => 28,
4 | 6 | 9 | 11 => 30,
_ => 31,
}
}
/// Returns the days from 1970-01-01 to the date. A year starts on 1 March
/// here, so the leap day is the last day of a year.
fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
let y = if month <= 2 { year - 1 } else { year };
let era = y.div_euclid(400);
let yoe = y - era * 400;
let doy = (153 * (if month > 2 { month - 3 } else { month + 9 }) + 2) / 5 + day - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
era * 146_097 + doe - 719_468
}
/// Returns the date that is the given number of days after 1970-01-01.
fn civil_from_days(days: i64) -> (i64, i64, i64) {
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = doy - (153 * mp + 2) / 5 + 1;
let month = if mp < 10 { mp + 3 } else { mp - 9 };
let year = yoe + era * 400 + i64::from(month <= 2);
(year, month, day)
}
tests/to_utc_test.rs 135 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/parse-and-format-a-date/.
use algo_parse_and_format_a_date::to_utc;
// (case, input, expected value)
const CASES: [(&str, &str, &str); 19] = [
("utc", "2026-11-10T12:00:00Z", "2026-11-10T12:00:00.000Z"),
(
"positive-offset",
"2026-11-10T19:30:00+07:00",
"2026-11-10T12:30:00.000Z",
),
(
"negative-offset",
"2026-11-10T07:00:00-05:00",
"2026-11-10T12:00:00.000Z",
),
(
"back-a-day",
"2026-11-11T01:00:00+07:00",
"2026-11-10T18:00:00.000Z",
),
(
"forward-a-day",
"2026-11-10T22:00:00-05:00",
"2026-11-11T03:00:00.000Z",
),
(
"year-end",
"2027-01-01T00:30:00+01:00",
"2026-12-31T23:30:00.000Z",
),
(
"leap-day",
"2024-02-29T23:00:00-02:00",
"2024-03-01T01:00:00.000Z",
),
(
"half-hour-offset",
"2026-11-10T17:30:00+05:30",
"2026-11-10T12:00:00.000Z",
),
(
"quarter-hour-offset",
"2026-11-10T17:45:00+05:45",
"2026-11-10T12:00:00.000Z",
),
(
"unknown-offset",
"2026-11-10T12:00:00-00:00",
"2026-11-10T12:00:00.000Z",
),
(
"fraction-one-digit",
"2026-11-10T12:00:00.5Z",
"2026-11-10T12:00:00.500Z",
),
(
"fraction-three-digits",
"2026-11-10T12:00:00.123+01:00",
"2026-11-10T11:00:00.123Z",
),
(
"before-epoch",
"1970-01-01T00:30:00+01:00",
"1969-12-31T23:30:00.000Z",
),
(
"before-epoch-fraction",
"1969-12-31T23:59:59.999Z",
"1969-12-31T23:59:59.999Z",
),
(
"largest-offset",
"2026-11-10T00:00:00+14:00",
"2026-11-09T10:00:00.000Z",
),
(
"smallest-offset",
"2026-11-10T00:00:00-12:00",
"2026-11-10T12:00:00.000Z",
),
(
"lower-case",
"2026-11-10t12:00:00z",
"2026-11-10T12:00:00.000Z",
),
(
"year-one",
"0001-01-01T00:00:00Z",
"0001-01-01T00:00:00.000Z",
),
(
"year-9999",
"9999-12-31T23:59:59.999Z",
"9999-12-31T23:59:59.999Z",
),
];
// (case, input that is not a valid RFC 3339 date-time)
const ERRORS: [(&str, &str); 18] = [
("no-offset", "2026-11-10T12:00:00"),
("date-only", "2026-11-10"),
("space-separator", "2026-11-10 12:00:00Z"),
("no-seconds", "2026-11-10T12:00Z"),
("offset-no-colon", "2026-11-10T12:00:00+0700"),
("offset-hours-only", "2026-11-10T12:00:00+07"),
("not-a-leap-year", "2026-02-29T12:00:00Z"),
("april-31", "2026-04-31T12:00:00Z"),
("month-13", "2026-13-01T12:00:00Z"),
("day-zero", "2026-11-00T12:00:00Z"),
("hour-24", "2026-11-10T24:00:00Z"),
("minute-60", "2026-11-10T12:60:00Z"),
("leap-second", "2016-12-31T23:59:60Z"),
("offset-hour-24", "2026-11-10T12:00:00+24:00"),
("offset-minute-60", "2026-11-10T12:00:00+07:60"),
("comma-fraction", "2026-11-10T12:00:00,5Z"),
("trailing-space", "2026-11-10T12:00:00Z "),
("empty", ""),
];
#[test]
fn converts_to_utc() {
for (name, timestamp, want) in CASES {
assert_eq!(to_utc(timestamp).as_deref(), Ok(want), "case {name}");
}
}
#[test]
fn rejects_invalid_input() {
for (name, timestamp) in ERRORS {
assert!(to_utc(timestamp).is_err(), "case {name}");
}
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/parse-and-format-a-date/.
# The date command differs between systems: GNU date has -d, and BSD date has
# -j and -f. So this file parses the text with [[ =~ ]] and counts days with
# the integer arithmetic of the shell, which is the same on every system.
# The date-time of RFC 3339 section 5.6, with a fraction of 1 to 3 digits.
# The groups: 1 year, 2 month, 3 day, 4 hour, 5 minute, 6 second, 7 fraction,
# 8 Z or offset, 9 offset sign, 10 offset hours, 11 offset minutes.
TO_UTC_RFC3339='^([0-9]{4})-([0-9]{2})-([0-9]{2})[Tt]([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])(\.[0-9]{1,3})?([Zz]|([+-])([01][0-9]|2[0-3]):([0-5][0-9]))$'
# _days_from_civil YEAR MONTH DAY
# Sets _days to the days from 1970-01-01 to the date (Howard Hinnant). A year
# starts on 1 March here, so the leap day is the last day. The shell rounds a
# division toward zero, so the year must be 1 or more.
_days_from_civil() {
local y=$1 m=$2 d=$3 era yoe doy doe
((y -= m <= 2, era = y / 400, yoe = y - era * 400))
((doy = (153 * (m > 2 ? m - 3 : m + 9) + 2) / 5 + d - 1))
((doe = yoe * 365 + yoe / 4 - yoe / 100 + doy))
((_days = era * 146097 + doe - 719468))
}
# _civil_from_days DAYS
# Sets _year, _month and _day to the date DAYS days after 1970-01-01.
_civil_from_days() {
local z=$(($1 + 719468)) era doe yoe doy mp
((era = z / 146097, doe = z - era * 146097))
((yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365))
((doy = doe - (365 * yoe + yoe / 4 - yoe / 100), mp = (5 * doy + 2) / 153))
((_day = doy - (153 * mp + 2) / 5 + 1, _month = mp < 10 ? mp + 3 : mp - 9))
((_year = yoe + era * 400 + (_month <= 2)))
}
# to_utc TIMESTAMP
# Prints the instant of an RFC 3339 timestamp in UTC, as
# YYYY-MM-DDTHH:MM:SS.sssZ. Prints an error and returns 1 when TIMESTAMP is
# not an RFC 3339 date-time with an offset, or when its date is not in the
# calendar.
to_utc() {
local ts=$1 year month day hour minute second fraction offset=0 max total
local _days _year _month _day
if ! [[ $ts =~ $TO_UTC_RFC3339 ]]; then
printf 'to_utc: not an RFC 3339 date-time: "%s"\n' "$ts" >&2
return 1
fi
# 10# reads "08" as eight. With no base, a leading 0 means octal.
year=$((10#${BASH_REMATCH[1]})) month=$((10#${BASH_REMATCH[2]}))
day=$((10#${BASH_REMATCH[3]})) hour=$((10#${BASH_REMATCH[4]}))
minute=$((10#${BASH_REMATCH[5]})) second=$((10#${BASH_REMATCH[6]}))
# The fraction: 1 to 3 digits, padded to milliseconds.
fraction=${BASH_REMATCH[7]#.}000
fraction=$((10#${fraction:0:3}))
if [[ -n ${BASH_REMATCH[9]} ]]; then
offset=$((10#${BASH_REMATCH[10]} * 3600 + 10#${BASH_REMATCH[11]} * 60))
if [[ ${BASH_REMATCH[9]} == - ]]; then offset=$((-offset)); fi
fi
case $month in
1 | 3 | 5 | 7 | 8 | 10 | 12) max=31 ;;
4 | 6 | 9 | 11) max=30 ;;
2) max=$((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) ? 29 : 28)) ;;
*) max=0 ;;
esac
if ((day < 1 || day > max)); then
printf 'to_utc: not a date in the calendar: "%s"\n' "$ts" >&2
return 1
fi
_days_from_civil "$year" "$month" "$day"
((total = (_days * 86400 + hour * 3600 + minute * 60 + second - offset) * 1000 + fraction))
# Round the days down, also for an instant before 1970.
((_days = total / 86400000, total %= 86400000))
if ((total < 0)); then ((total += 86400000, _days -= 1)); fi
_civil_from_days "$_days"
printf '%04d-%02d-%02dT%02d:%02d:%02d.%03dZ\n' "$_year" "$_month" "$_day" \
$((total / 3600000)) $((total / 60000 % 60)) $((total / 1000 % 60)) $((total % 1000))
}
test_to_utc.bats 60 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/parse-and-format-a-date/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/to_utc.sh"
}
converts() { # converts TIMESTAMP WANT
run --separate-stderr to_utc "$1"
[ "$status" -eq 0 ]
[ "$output" = "$2" ]
}
rejects() { # rejects TIMESTAMP
run --separate-stderr to_utc "$1"
[ "$status" -eq 1 ]
[ -z "$output" ]
[ -n "$stderr" ]
}
@test "utc" { converts "2026-11-10T12:00:00Z" "2026-11-10T12:00:00.000Z"; }
@test "positive-offset" { converts "2026-11-10T19:30:00+07:00" "2026-11-10T12:30:00.000Z"; }
@test "negative-offset" { converts "2026-11-10T07:00:00-05:00" "2026-11-10T12:00:00.000Z"; }
@test "back-a-day" { converts "2026-11-11T01:00:00+07:00" "2026-11-10T18:00:00.000Z"; }
@test "forward-a-day" { converts "2026-11-10T22:00:00-05:00" "2026-11-11T03:00:00.000Z"; }
@test "year-end" { converts "2027-01-01T00:30:00+01:00" "2026-12-31T23:30:00.000Z"; }
@test "leap-day" { converts "2024-02-29T23:00:00-02:00" "2024-03-01T01:00:00.000Z"; }
@test "half-hour-offset" { converts "2026-11-10T17:30:00+05:30" "2026-11-10T12:00:00.000Z"; }
@test "quarter-hour-offset" { converts "2026-11-10T17:45:00+05:45" "2026-11-10T12:00:00.000Z"; }
@test "unknown-offset" { converts "2026-11-10T12:00:00-00:00" "2026-11-10T12:00:00.000Z"; }
@test "fraction-one-digit" { converts "2026-11-10T12:00:00.5Z" "2026-11-10T12:00:00.500Z"; }
@test "fraction-three-digits" { converts "2026-11-10T12:00:00.123+01:00" "2026-11-10T11:00:00.123Z"; }
@test "before-epoch" { converts "1970-01-01T00:30:00+01:00" "1969-12-31T23:30:00.000Z"; }
@test "before-epoch-fraction" { converts "1969-12-31T23:59:59.999Z" "1969-12-31T23:59:59.999Z"; }
@test "largest-offset" { converts "2026-11-10T00:00:00+14:00" "2026-11-09T10:00:00.000Z"; }
@test "smallest-offset" { converts "2026-11-10T00:00:00-12:00" "2026-11-10T12:00:00.000Z"; }
@test "lower-case" { converts "2026-11-10t12:00:00z" "2026-11-10T12:00:00.000Z"; }
@test "year-one" { converts "0001-01-01T00:00:00Z" "0001-01-01T00:00:00.000Z"; }
@test "year-9999" { converts "9999-12-31T23:59:59.999Z" "9999-12-31T23:59:59.999Z"; }
@test "no-offset" { rejects "2026-11-10T12:00:00"; }
@test "date-only" { rejects "2026-11-10"; }
@test "space-separator" { rejects "2026-11-10 12:00:00Z"; }
@test "no-seconds" { rejects "2026-11-10T12:00Z"; }
@test "offset-no-colon" { rejects "2026-11-10T12:00:00+0700"; }
@test "offset-hours-only" { rejects "2026-11-10T12:00:00+07"; }
@test "not-a-leap-year" { rejects "2026-02-29T12:00:00Z"; }
@test "april-31" { rejects "2026-04-31T12:00:00Z"; }
@test "month-13" { rejects "2026-13-01T12:00:00Z"; }
@test "day-zero" { rejects "2026-11-00T12:00:00Z"; }
@test "hour-24" { rejects "2026-11-10T24:00:00Z"; }
@test "minute-60" { rejects "2026-11-10T12:60:00Z"; }
@test "leap-second" { rejects "2016-12-31T23:59:60Z"; }
@test "offset-hour-24" { rejects "2026-11-10T12:00:00+24:00"; }
@test "offset-minute-60" { rejects "2026-11-10T12:00:00+07:60"; }
@test "comma-fraction" { rejects "2026-11-10T12:00:00,5Z"; }
@test "trailing-space" { rejects "2026-11-10T12:00:00Z "; }
@test "empty" { rejects ""; }
References
- RFC 3339, Date and Time on the Internet: Timestamps, 4.2 Local Offsets, 4.3 Unknown Local Offset Convention, 5.6 Internet Date/Time Format, 5.7 Restrictions
- The Python Standard Library, datetime, Basic date and time types, Aware and Naive Objects, datetime.fromisoformat, datetime.astimezone, datetime.isoformat
- The Python Standard Library, re, Regular expression operations, \d, $, re.fullmatch
- MDN Web Docs, Date, Date time string format, Date components and time zones
- MDN Web Docs, Date.prototype.toISOString(), Return value, Exceptions
- Java SE 25 API, java.time.format.DateTimeFormatter, Patterns for Formatting and Parsing, ISO_OFFSET_DATE_TIME
- Java SE 25 API, java.time.format.ResolverStyle, STRICT, SMART, LENIENT
- .NET API reference, DateTimeOffset.ParseExact, ParseExact(String, String[], IFormatProvider, DateTimeStyles), Remarks, Exceptions
- .NET, Custom date and time format strings, The "MM", "mm", "FFF", "fff", "zzz" and "yyyy" custom format specifiers
- .NET, Character classes in regular expressions, Decimal digit character: \d
- .NET, Anchors in regular expressions, End of String or Line: $, End of String Only: \z
- Go standard library, package time, Constants (RFC3339 and the layout rules), Parse
- The Rust Standard Library, std::time, Structs
- Howard Hinnant, chrono-Compatible Low-Level Date Algorithms, days_from_civil, civil_from_days
- cppreference.com, std::chrono::year_month_day::ok
- cppreference.com, std::formatter<std::chrono::sys_time>, Format specification, %F, %T, %S
- cppreference.com, C arithmetic operators, Division
- bash(1) manual page, Compound Commands ([[ expression ]], =~), ARITHMETIC EVALUATION
- date(1) manual page, GNU coreutils, -d, --date
- FreeBSD manual page, date(1), -j, -f
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
The native tests pass in 9 of 10 languages in this build.
Tag YTSBW9 Edit this page History Report an error Markdown