std.datetime - D Programming Language
Description: D Programming Language
Keywords: D programming language

Menu

- Learn
- Documentation
  - Language Reference
  - Library Reference
  - Command-line Reference
  - Feature Overview
  - Articles
- Packages
- Community
  - Blog
  - Orgs using D
  - Twitter
  - Forums
  - IRC
  - Wiki
  - GitHub
  - Issues
  - Foundation
  - Donate
- Resources
  - Books
  - Tutorials
  - Tools
  - Editors
  - IDEs
  - Visual D
  - Acknowledgments
  - D Style
  - Glossary
  - Sitemap

Search
Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using a local clone.

# std.datetime

Module containing Date/Time functionality.
This module provides:

- Types to represent points in time: std.datetime.systime.SysTime, std.datetime.date.Date, std.datetime.date.TimeOfDay, std.datetime.date.DateTime.
- Types to represent intervals of time.
- Types to represent ranges over intervals of time.
- Types to represent time zones (used by std.datetime.systime.SysTime).
- A platform-independent, high precision stopwatch type: StopWatch
- Benchmarking functions.
- Various helper functions.

Closely related to std.`datetime` is core.time, and some of the time types used in std.`datetime` come from there - such as core.time.Duration, core.time.TickDuration, and core.time.FracSec. core.time is publically imported into std.`datetime`, it isn't necessary to import it separately.
Three of the main concepts used in this module are time points, time durations, and time intervals.
A time point is a specific point in time. e.g. January 5th, 2010 or 5:00.
A time duration is a length of time with units. e.g. 5 days or 231 seconds.
A time interval indicates a period of time associated with a fixed point in time. It is either two time points associated with each other, indicating the time starting at the first point up to, but not including, the second point - e.g. [January 5th, 2010 - March 10th, 2010) - or it is a time point and a time duration associated with one another. e.g. January 5th, 2010 and 5 days, indicating [January 5th, 2010 - January 10th, 2010).
Various arithmetic operations are supported between time points and durations (e.g. the difference between two time points is a time duration), and ranges can be gotten from time intervals, so range-based operations may be done on a series of time points.
The types that the typical user is most likely to be interested in are std.datetime.date.Date (if they want dates but don't care about time), std.datetime.date.DateTime (if they want dates and times but don't care about time zones), std.datetime.systime.SysTime (if they want the date and time from the OS and/or do care about time zones), and StopWatch (a platform-independent, high precision stop watch). std.datetime.date.Date and std.datetime.date.DateTime are optimized for calendar-based operations, while std.datetime.systime.SysTime is designed for dealing with time from the OS. Check out their specific documentation for more details.
To get the current time, use std.datetime.systime.Clock.currTime. It will return the current time as a std.datetime.systime.SysTime. To print it, toString is sufficient, but if using toISOString, toISOExtString, or toSimpleString, use the corresponding fromISOString, fromISOExtString, or fromSimpleString to create a std.datetime.systime.SysTime from the string.

    auto currentTime = Clock.currTime();
    auto timeString = currentTime.toISOExtString();
    auto restoredTime = SysTime.fromISOExtString(timeString);

Various functions take a string (or strings) to represent a unit of time (e.g. convert!("days", "hours")(numDays)). The valid strings to use with such functions are "years", "months", "weeks", "days", "hours", "minutes", "seconds", "msecs" (milliseconds), "usecs" (microseconds), "hnsecs" (hecto-nanoseconds - i.e. 100 ns), or some subset thereof. There are a few functions in core.time which take "nsecs", but because nothing in std.`datetime` has precision greater than hnsecs, and very little in core.time does, no functions in std.`datetime` accept "nsecs". To remember which units are abbreviated and which aren't, all units seconds and greater use their full names, and all sub-second units are abbreviated (since they'd be rather long if they weren't).

Note: std.datetime.date.DateTimeException is an alias for core.time.TimeException, so you don't need to worry about core.time functions and std.`datetime` functions throwing different exception types (except in the rare case that they throw something other than core.time.TimeException or std.datetime.date.DateTimeException).

See Also:
Introduction to std.datetime
ISO 8601
Wikipedia entry on TZ Database
List of Time Zones
License:
Boost License 1.0.
Authors:
Jonathan M Davis and Kato Shoichi

Source: std/datetime/package.d

alias `AutoStart` = std.typecons.Flag!"autoStart".Flag;
  Used by StopWatch to indicate whether it should start immediately upon construction.
  If set to `AutoStart`.no, then the stopwatch is not started when it is constructed.
  Otherwise, if set to `AutoStart`.yes, then the stopwatch is started when it is constructed.
struct `StopWatch`;
  This will be deprecated in 2.076. Please use `StopWatch`">std.datetime.stopwatch.`StopWatch` instead. It uses core.time.Monotime and core.time.Duration rather than core.time.TickDuration, which will also be deprecated in 2.076.
  `StopWatch` measures time as precisely as possible.
  This class uses a high-performance counter. On Windows systems, it uses QueryPerformanceCounter, and on Posix systems, it uses clock_gettime if available, and gettimeofday otherwise.
  But the precision of `StopWatch` differs from system to system. It is impossible to for it to be the same from system to system since the precision of the system clock varies from system to system, and other system-dependent and situation-dependent stuff (such as the overhead of a context switch between threads) can also affect `StopWatch`'s accuracy.
  Examples:

      void writeln(S...)(S args){}
      static void bar() {}

      StopWatch sw;
      enum n = 100;
      TickDuration[n] times;
      TickDuration last = TickDuration.from!"seconds"(0);
      foreach (i; 0 .. n)
      {
         sw.start(); //start/resume mesuring.
         foreach (unused; 0 .. 1_000_000)
             bar();
         sw.stop();  //stop/pause measuring.
         //Return value of peek() after having stopped are the always same.
         writeln((i + 1) * 1_000_000, " times done, lap time: ",
                 sw.peek().msecs, "[ms]");
         times[i] = sw.peek() - last;
         last = sw.peek();
      }
      real sum = 0;
      // To get the number of seconds,
      // use properties of TickDuration.
      // (seconds, msecs, usecs, hnsecs)
      foreach (t; times)
         sum += t.hnsecs;
      writeln("Average time: ", sum/n, " hnsecs");

  @nogc @safe this(AutoStart `autostart`);
    Auto start with constructor.
  const pure nothrow @nogc @safe bool `opEquals`(const StopWatch `rhs`);
  const pure nothrow @nogc @safe bool `opEquals`(ref const StopWatch `rhs`);
  @nogc @safe void `reset`();
    Resets the stop watch.
    Examples:

        StopWatch sw;
        sw.start();
        sw.stop();
        sw.reset();
        assert(sw.peek().to!("seconds", real)() == 0);

  @nogc @safe void `start`();
    Starts the stop watch.
  @nogc @safe void `stop`();
    Stops the `stop` watch.
  const @nogc @safe TickDuration `peek`();
    Peek at the amount of time which has passed since the stop watch was started.
  @nogc @safe void `setMeasured`(TickDuration `d`);
    Set the amount of time which has been measured since the stop watch was started.
  const pure nothrow @nogc @property @safe bool `running`();
    Confirm whether this stopwatch is measuring time.
TickDuration[fun.length] `benchmark`(fun...)(uint `n`);
  This will be deprecated in 2.076. Please use `benchmark`">std.datetime.stopwatch.`benchmark` instead. It uses core.time.Monotime and core.time.Duration rather than core.time.TickDuration, which will also be deprecated in 2.076.
  Benchmarks code for speed assessment and comparison.
  Parameters:

  fun | aliases of callable objects (e.g. function names). Each should take no arguments.
  uint `n` | The number of times each function is to be executed.

  Returns:
  The amount of time (as a core.time.TickDuration) that it took to call each function `n` times. The first value is the length of time that it took to call fun[0] `n` times. The second value is the length of time it took to call fun[1] `n` times. Etc.
  Note that casting the TickDurations to core.time.Durations will make the results easier to deal with (and it may change in the future that `benchmark` will return an array of Durations rather than TickDurations).
  See Also:
  measureTime
  Examples:

      import std.conv : to;
      int a;
      void f0() {}
      void f1() {auto b = a;}
      void f2() {auto b = to!string(a);}
      auto r = benchmark!(f0, f1, f2)(10_000);
      auto f0Result = to!Duration(r[0]); // time f0 took to run 10,000 times
      auto f1Result = to!Duration(r[1]); // time f1 took to run 10,000 times
      auto f2Result = to!Duration(r[2]); // time f2 took to run 10,000 times

struct `ComparingBenchmarkResult`;
  Return value of benchmark with two functions comparing.
  const pure nothrow @property @safe real `point`();
    Evaluation value
    This returns the evaluation value of performance as the ratio of baseFunc's time over targetFunc's time. If performance is high, this returns a high value.
  const pure nothrow @property @safe TickDuration `baseTime`();
    The time required of the base function
  const pure nothrow @property @safe TickDuration `targetTime`();
    The time required of the target function
ComparingBenchmarkResult `comparingBenchmark`(alias baseFunc, alias targetFunc, int times = 4095)();
  This will be deprecated in 2.076. Please use std.datetime.stopwatch.benchmark instead. This function has not been ported to core.time.Monotime and core.time.Duration, because it is a trivial wrapper around benchmark.
  Benchmark with two functions comparing.
  Parameters:

  baseFunc | The function to become the base of the speed.
  targetFunc | The function that wants to measure speed.
  times | The number of times each function is to be executed.

  Examples:

      void f1x() {}
      void f2x() {}
      @safe void f1o() {}
      @safe void f2o() {}
      auto b1 = comparingBenchmark!(f1o, f2o, 1)(); // OK
      //writeln(b1.point);

@safe auto `measureTime`(alias func)()
if (isSafe!(() { StopWatch sw; unaryFun!func(sw.peek()); } ));
  This will be deprecated in 2.076. Please use std.datetime.stopwatch.StopWatch instead. This function has not been ported to core.time.Monotime and core.time.Duration, because it is a trivial wrapper around StopWatch.
  Function for starting to a stop watch time when the function is called and stopping it when its return value goes out of scope and is destroyed.
  When the value that is returned by this function is destroyed, func will run. func is a unary function that takes a core.time.TickDuration.

  Example:

      {
          auto mt = measureTime!((TickDuration a)
              { /+ do something when the scope is exited +/ });
          // do something that needs to be timed
      }

  which is functionally equivalent to

      {
          auto sw = StopWatch(Yes.autoStart);
          scope(exit)
          {
              TickDuration a = sw.peek();
              /+ do something when the scope is exited +/
          }
          // do something that needs to be timed
      }

  See Also:
  benchmark

Copyright © 1999-2017 by the D Language Foundation | Page generated by Ddoc on Thu Aug 10 17:51:10 2017