Date Formating

Jonathan M Davis newsgroup.d at jmdavisprog.com
Wed Dec 13 07:35:40 UTC 2017


On Wednesday, December 13, 2017 02:34:12 codephantom via Digitalmars-d-learn 
wrote:
> On Tuesday, 12 December 2017 at 15:56:59 UTC, Vino wrote:
> > Hi All,
> >
> >   Request out help on date formatting, I have code which output
> >
> > the date and time as below , i we need it without the last few
> > numbers.,ie "YYYY-MMM-DD HH:MM:SI"
> >
> > Output : 2017-Sep-06 16:06:42.7223837
> > Required Output : 2017-Sep-06 16:06:42
> >
> > From,
> > Vino.B
>
> just playing with this...
>
> // ----------
>
> module test;
>
> void main()
> {
>      import std.stdio;
>
>      writeln( GetFmtDate() ); // e.g: 2017-Dec-13 13:30:23
>
> }
>
>
> string GetFmtDate()
> {
>      import std.datetime;
>      import std.ascii : toUpper;
>      import std.conv : to;
>      import std.string : format;
>
>      auto d = Clock.currTime();
>
>      string fmtMonth = toUpper(to!string(d.month)[0]) ~
>                                to!string(d.month)[1..$];
>
>      return
>              format("%04s-%s-%02s %02s:%02s:%02s",
>                  (d.year),
>                  fmtMonth,
>                  (d.day),
>                  (d.hour),
>                  (d.minute),
>                  (d.second)
>                  );
> }
>
> // --------------

In general, you probably want to cast the SysTime to a DateTime if you're
going to do something like that. There's a lot of duplicate work being done
if you get each of those properties individually, whereas if you cast to
DateTime, then it does the work once, and the properties for DateTime just
return the correspending member variables. Sometimes, I think that putting
year, month, etc. on SysTime was a mistake, because using thoes properties
almost always the wrong thing to do given how much work is duplicated when
using them, but at the same time, there are cases where the efficiency
doesn't really matter and the simplicity of just grabbing the properties
from SysTime is nice.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list