D:打印当前月份的数字而不是它的名字

D: print number of current month instead of its name

我需要获取当前月份的数字而不是其名称:

void main()
{
    SysTime dt = Clock.currTime();
    writeln(dt.month);
}

输出为:

oct

但我需要 10。我怎样才能得到它? castint我只找到一个解决办法,但是有没有更好的办法,还是可以的?

使用 std.conv.to() 转换类型。

这似乎有效:

import std.conv;
import std.datetime;
import std.stdio;

void main()
{
    SysTime dt = Clock.currTime();
    writeln(dt.month.to!ushort);
}

10

不需要显式转换,因为 Month 枚举的类型默认为 int(查看有关 enums 的更多信息)。

import std.datetime;

// Month is an enum - http://dlang.org/phobos/std_datetime.html#.Month
Month month = Clock.currTime().month;
int monthnum = 0 + month; // works

如果您只是需要它来打印,请像下面那样使用 writefln

writefln("%d", dt.month);

如果您需要使用号码,那么可以使用to模板,一般情况下应该使用该模板进行转换。

writeln(dt.month.to!size_t);
// or ...
writeln(to!size_t(dt.month));

最终你也可以投了

writeln(cast(size_t)dt.month);