www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Can't get expected strings

reply helxi <brucewayneshit gmail.com> writes:
import std.stdio, std.datetime, std.conv, std.algorithm;

void main()
{
     immutable DEADLINE = DateTime(2017, 7, 16, 23, 59, 
59).to!SysTime;
     immutable NOW = Clock.currTime;
     immutable INTERVAL = (DEADLINE - NOW)
                         .abs
                         .to!string;
                         //if I put .until("secs") here, it prints 
the full-type
                         //immutable(Until!("a == b", string, 
string))("1 day, 23 hours, 47 minutes, 30 secs, 508 ms, 119 μs, 
and 6 hnsecs", "secs", yes, false)


     writeln(INTERVAL);

     //But I don't want these until("secs") below:
     if (NOW > DEADLINE) writeln(INTERVAL.until("secs"), "seconds 
ago.");
     //1 day, 23 hours, 48 minutes, 55 seconds ago.
     else if (NOW < DEADLINE) writeln(INTERVAL.until("secs"), 
"seconds ahead.");
     else writeln("Now.");
}

-----


Why is to!string providing inconsistent string?
Jul 18
parent Jonathan M Davis via Digitalmars-d-learn writes:
On Tuesday, July 18, 2017 13:49:11 helxi via Digitalmars-d-learn wrote:
 import std.stdio, std.datetime, std.conv, std.algorithm;

 void main()
 {
      immutable DEADLINE = DateTime(2017, 7, 16, 23, 59,
 59).to!SysTime;
      immutable NOW = Clock.currTime;
      immutable INTERVAL = (DEADLINE - NOW)
                          .abs
                          .to!string;
                          //if I put .until("secs") here, it prints
 the full-type
                          //immutable(Until!("a == b", string,
 string))("1 day, 23 hours, 47 minutes, 30 secs, 508 ms, 119 μs,
 and 6 hnsecs", "secs", yes, false)


      writeln(INTERVAL);

      //But I don't want these until("secs") below:
      if (NOW > DEADLINE) writeln(INTERVAL.until("secs"), "seconds
 ago.");
      //1 day, 23 hours, 48 minutes, 55 seconds ago.
      else if (NOW < DEADLINE) writeln(INTERVAL.until("secs"),
 "seconds ahead.");
      else writeln("Now.");
 }

 -----


 Why is to!string providing inconsistent string?
Because the output of Duration.toString strips any units that are 0. It's intended to be human readable, not machine parseable. If you want a specific format, I'd suggest that you grab the units on your own and create the string that you want rather than trying to parse the result of toString. If you want the entire Duration in seconds, then do something like auto diff = Clock.currTime - deadline; writefln("%s seconds ago", diff.total!"seconds"); whereas if you want to split out the units so that you get the seconds portion beyond the minute, then you'd do something like auto diff = Clock.currTime - deadline; writefln("%s seconds ago", diff.split!("minutes", "seconds").seconds); http://dlang.org/phobos/core_time.html#.Duration.total http://dlang.org/phobos/core_time.html#.Duration.split - Jonathan M Davis
Jul 18