I\'m using a DateTime
in C# to display times. What date portion does everyone use when constructing a time?
E.g. the following is not valid because ther
To display a TimeSpan formatted with local culture, simply add it to a date like DateTime.Today. Something like this:
(DateTime.Today + timeSpan).ToString();
Since your value really doesn't represent a date, you're better off storing it as a TimeSpan until the time comes to display it.
A TimeSpan most certainly can store the time of the day - you just have to treat the value as the amount of time elapsed since midnight, basically the same way we read a clock.
You can just create a new DateTime with a string literal.
String literal for time:
DateTime t = new DateTime("01:00:30");
String literal for date:
DateTime t = new DateTime("01/05/2008"); // english format
DateTime t = new DateTime("05.01.2008"); // german format
For a DateTime with date and time values:
DateTime t = new DateTime("01/05/2008T01:00:30");
In most cases, when creating a DateTime, i set it to DateTime.Now, if it is not actually set to anything else. If you instantiate an DateTime manually, you should beware of the DateTimeKind set correctly, otherwise this could lead to surprises.
what about DateTime.MinValue?
Personally I'd create a custom Time
struct
that contains a DateTime
instance, and which has similar properties, constructors etc. but doesn't expose days/months/etc. Just make all your public accessors pass through to the contained instance. Then you can simply have the epoch as a private static readonly DateTime
field and it doesn't matter what value you choose as it's all neatly contained within your custom struct. In the rest of your code can simply write:
var time = new Time(16, 47, 58);
May I suggest that in some cases a custom struct could do? It could have an Int32 backing value (there are 86 milion milliseconds in a day; this would fit in an Int32).
There could be get-only properties :
Hours Minutes Seconds Milliseconds
You could also overload operators such as +, - and so on. Implement IEquatable, IComparable and whatever may be the case. Overload Equals, == . Overload and override ToString.
You could also provide more methods to construct from a DateTime or append to a datetime and so on.