Time Formatting Parsing in D Programming Language
import std.stdio;
import std.datetime;
void main()
{
// Here's a basic example of formatting a time
// according to RFC3339, using the corresponding layout
// constant.
auto t = Clock.currTime();
writeln(t.toISOExtString());
// Time parsing uses the same layout values as format.
auto t1 = SysTime.fromISOExtString("2012-11-01T22:08:41+00:00");
writeln(t1);
// Format and parse use example-based layouts. Usually
// you'll use a constant from std.datetime for these layouts, but
// you can also supply custom layouts.
writeln(t.toSimpleString());
writeln(t.toString());
// For purely numeric representations you can also
// use standard string formatting with the extracted
// components of the time value.
writefln("%d-%02d-%02dT%02d:%02d:%02d-00:00",
t.year, t.month, t.day,
t.hour, t.minute, t.second);
// Parse will return an exception on malformed input
// explaining the parsing problem.
try
{
auto _ = SysTime.fromSimpleString("8:41PM");
}
catch (Exception e)
{
writeln(e.msg);
}
}
This D code demonstrates time formatting and parsing, which is similar to the original Go example. Here’s a breakdown of the changes and explanations:
We import
std.stdio
for input/output operations andstd.datetime
for time-related functions.The
time.Now()
function is replaced withClock.currTime()
in D.D uses
toISOExtString()
to format time according to RFC3339.For parsing, D uses
SysTime.fromISOExtString()
instead oftime.Parse()
.D doesn’t have exact equivalents for all Go’s time formatting patterns, so we use
toSimpleString()
andtoString()
to demonstrate different formatting options.The custom formatting example is similar, using
writefln()
to format the time components.For error handling in parsing, D uses exceptions instead of returning an error. We demonstrate this with a try-catch block.
To run this program, save it as time_formatting_parsing.d
and use the D compiler:
$ dmd time_formatting_parsing.d
$ ./time_formatting_parsing
This will compile and run the program, displaying various formatted times and demonstrating time parsing.