我用dlang语言实现的php的date函数代码如下import stdstdio;import stddatetime;import stddatetimesystime SysTime;import stdconv;import coretime;import stddatetimetimezone UTC;string datestring format long timestamp = -
在D语言中,TimeStamp被重命名为SysTime,您需要将代码中的TimeStamp替换为SysTime。另外,Month.to!string("%B")返回的是wstring类型,需要使用to!string(to!wstring(datetime.month.to!string("%B")))来转换为string类型。修改后的代码如下:
import std.stdio; import std.datetime; import std.datetime.systime: SysTime; import std.conv; import core.time; import std.datetime.timezone: UTC;
string date(string format, long timestamp = -1) { SysTime datetime; if (timestamp == -1) { datetime = Clock.currTime().toUTC(); } else { datetime = SysTime(SysTime(Date.init, TimeStamp(timestamp)), UTC()); }
string result = "";
foreach (char c; format) {
switch (c) {
case 'Y': result ~= to!string(datetime.year); break;
case 'm': result ~= formatIntWidth2(datetime.month); break;
case 'd': result ~= formatIntWidth2(datetime.day); break;
case 'H': result ~= formatIntWidth2(datetime.hour); break;
case 'i': result ~= formatIntWidth2(datetime.minute); break;
case 's': result ~= formatIntWidth2(datetime.second); break;
case 'F': result ~= to!string(to!wstring(datetime.month.to!string("%B"))); break;
case 'j': result ~= to!string(datetime.day); break;
case 'n': result ~= to!string(datetime.month); break;
case 'g': result ~= formatHour12(datetime.hour); break;
case 'a': result ~= formatAmPm(datetime.hour); break;
case 'D': result ~= to!string(to!wstring(datetime.dayOfWeek.to!string("%a"))); break;
case 'M': result ~= to!string(to!wstring(datetime.month.to!string("%b"))); break;
case 'G': result ~= to!string(datetime.hour); break;
case 'T': result ~= datetime.timezone.toString(); break;
default: result ~= c; break;
}
}
return result;
}
string formatIntWidth2(int value) { if (value < 10) { return "0" ~ to!string(value); } else { return to!string(value); } }
string formatHour12(int hour) { int hour12 = (hour % 12 == 0) ? 12 : hour % 12; return to!string(hour12); }
string formatAmPm(int hour) { return (hour < 12) ? "am" : "pm"; }
long time() { return Clock.currTime().toUTC().toUnixTime(); }
// 示例代码 void main() { writeln("当前时间: "); writeln(date("F j, Y, g:i a")); writeln(date("m.d.y")); writeln(date("j, n, Y")); writeln(date("Ymd")); writeln(date("h-i-s, j-m-y, it is w Day")); // 毫秒部分未实现 writeln(date("\i\t \i\s \t\h\e jS \d\a\y.")); writeln(date("D M j G:i:s T Y")); writeln(date("H:m:s \m \i\s\ \m\o\n\t\h")); writeln(date("H:i:s")); writeln(date("Y-m-d H:i:s"));
原文地址: https://www.cveoy.top/t/topic/fCyI 著作权归作者所有。请勿转载和采集!