C# DateTime: What “date” to use when I'm using just the “time”?

后端 未结 12 1564
陌清茗
陌清茗 2020-12-16 09:35

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

相关标签:
12条回答
  • 2020-12-16 10:17

    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.

    0 讨论(0)
  • 2020-12-16 10:20

    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.

    0 讨论(0)
  • 2020-12-16 10:21

    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.

    0 讨论(0)
  • 2020-12-16 10:22

    what about DateTime.MinValue?

    0 讨论(0)
  • 2020-12-16 10:24

    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);
    
    0 讨论(0)
  • 2020-12-16 10:27

    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.

    0 讨论(0)
提交回复
热议问题