August 22, 2016 Re: Get current date and time with std.datetime | ||||
---|---|---|---|---|
| ||||
Posted in reply to Zekereth | On Friday, 1 July 2016 at 15:28:04 UTC, Zekereth wrote: > On Thursday, 30 June 2016 at 21:18:22 UTC, Luke Picardo wrote: >> >> Why is it so hard to simply get the current date and time formatted properly in a string? >> >> There are no examples of this in your documentation yet this is probably one of the most used cases. > > To get the current time, use Clock.currTime. It will return the current time as a SysTime. To print it, toString is sufficient, but if using toISOString, toISOExtString, or toSimpleString, use the corresponding fromISOString, fromISOExtString, or fromSimpleString to create a SysTime from the string. > > auto currentTime = Clock.currTime(); > auto timeString = currentTime.toISOExtString(); > auto restoredTime = SysTime.fromISOExtString(timeString); This is what I use: auto getDateTimeString() { import std.string; import std.datetime; DateTime dateTime = cast(DateTime)Clock.currTime(); with(dateTime) { return format( "%s " // day of the week (eg. 'Saturday') "%s.%02s.%s " // date, month, year "[%s:%02s:%02s%s]", // hour:minute:second am/pm split("Sunday Monday Tuesday Wednesday Thursday Friday Saturday")[dayOfWeek], day, cast(int)month, year, hour == 0 || hour == 12 ? 12 : hour % 12, minute, second, hour <= 11 ? "am" : "pm"); } } |
Copyright © 1999-2021 by the D Language Foundation