我有一个这种格式的日期:Wdy, DD-Mon-YY HH:MM:SS GMT
我需要对其进行解析并将其转换为struct std.date.Date
或等价于。我通过使用split()
s 调用编写了一个非常简单的函数(请查看我的代码下方)。
问题在于性能——我正在寻找一种更快的算法来做到这一点。拆分令牌后,我使用to!int(tok)
转换为int
并放入结构中。有没有最好的方法呢?如果不太复杂,请建议内置 D 函数或一些外部模块。
注意:我是一名 C 程序员,从 D 编程语言开始。因此,您将看到一些 C-way 解决方案。
struct MyDate {
int day;
int month;
int year;
int hour;
int minute;
int second;
//int ms;
};
int index_of_month(string mont)
{
immutable string[] months = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
for(int i = 0, len = months.length; i < len; ++i)
if(months[i] == mont)
return i;
return -1;
}
void main()
{
//date format Wdy, DD-Mon-YY HH:MM:SS GMT
string d = "Sun, 24-Aug-2014 15:00:24 GMT";
string[] parts = split(d, " ");
string[] _date = split(parts[1], "-");
string[] _hour = split(parts[2], ":");
debug {
for(int i = 0; i < parts.length; ++i)
writefln("[%d]: %s", i, parts[i]);
} else {
//Handling erros goes here
//...
//I write my onw date struct because
// std.date.Date cannot be compiled
// even by using -d flag; and std.datetime.Date is not equivalent to.
// NOTE: I think that I will have problems when try to compare it
// to Clock.currTime()..
MyDate date;
//as you can seed below, I did a lot of
// string to integer conversion;
// I don't know much aboud D, but I think
// that it's so slow. I'm looking for a best
// solution(in perfomance questions).
date.day = to!int(_date[0]); // 0 .. 31 min/max 2 digits.
//I know about enum Month from std.datatime;
// but there is no(as far as I know) equivalent to Enum.GetValues()/Enum.GetNames()
// of C#.NET and .indexOf(), so I write my onw implemantation...
date.month = index_of_month(toLower(_date[1])); // 1 .. 12 min/max 2 digits.
//maybe do it by using e.g(C-way),
// int n = 0; n = (n * 10) + (_date[2][0] - '0'); n = (n * 10) + (_date[2][0] - '0'); and so..
// and lave the compiler do promotion
// can be better?
date.year = to!int(_date[2]); // min 2, max 4 digits.
date.hour = to!int(_hour[0]); // 0 .. 23 min/max 2 digits.
date.minute = to!int(_hour[1]); // 0 .. 59 min/max 2 digits.
date.second = to!int(_hour[2]); // 0 .. 59 min/max 2 digits.
writefln("date.day = %d\n"
"date.month = %d\n"
"date.year = %d\n"
"date.hour = %d\n"
"date.minute = %d\n"
"date.second = %d\n",
date.day, date.month,
date.year, date.hour,
date.minute, date.second);
}
}