我如何表示在。net中的时间值?

时间:2022-10-30 10:41:47

Is there a way one can represent a time only value in .NET without the date? For example, indicating the opening time of a shop?

有没有一种方法可以表示。net中没有日期的时间值?例如,指示商店的营业时间?

TimeSpan indicates a range, whereas I only want to store a time value. Using DateTime to indicate this would result in new DateTime(1,1,1,8,30,0) which is not really desirable.

TimeSpan表示一个范围,而我只想存储一个时间值。使用DateTime表明这将导致新的DateTime(1、1、1、8、30、0)。

7 个解决方案

#1


108  

As others have said, you can use a DateTime and ignore the date, or use a TimeSpan. Personally I'm not keen on either of these solutions, as neither type really reflects the concept you're trying to represent - I regard the date/time types in .NET as somewhat on the sparse side which is one of the reasons I started Noda Time. In Noda Time, you can use the LocalTime type to represent a time of day.

正如其他人所说,您可以使用DateTime并忽略日期,或者使用TimeSpan。我个人并不喜欢这些解决方案,因为这两种类型都不能真正反映出你想要表达的概念——我把。net中的日期/时间类型看作是在稀疏的方面,这也是我开始野田时间的原因之一。在野田时间,你可以使用当地时间类型来代表一天中的一个时间。

One thing to consider: the time of day is not necessarily the length of time since midnight on the same day...

要考虑的一件事是:白天的时间不一定是同一天午夜之后的时间长度……

(As another aside, if you're also wanting to represent a closing time of a shop, you may find that you want to represent 24:00, i.e. the time at the end of the day. Most date/time APIs - including Noda Time - don't allow that to be represented as a time-of-day value.)

(另一方面,如果你也想代表一个商店的关门时间,你可能会发现你想代表24:00,也就是一天结束的时间。大多数日期/时间api(包括野田时间)都不允许将其表示为一天的时间值。

#2


129  

You can use timespan

您可以使用时间间隔

TimeSpan timeSpan = new TimeSpan(2, 14, 18);
Console.WriteLine(timeSpan.ToString());     // Displays "02:14:18".

[Edit]
Considering the other answers and the edit to the question, I would still use TimeSpan. No point in creating a new structure where an existing one from the framework suffice.
On these lines you would end up duplicating many native data types.

[编辑]考虑到其他的答案和编辑的问题,我仍然会使用TimeSpan。没有必要创建一个新结构,而框架中的现有结构就足够了。在这些行中,您将最终复制许多本机数据类型。

#3


26  

If that empty Date really bugs you, you can also to create a simpler Time structure:

如果那个空的日期真的让你烦恼,你也可以创建一个更简单的时间结构:

// more work is required to make this even close to production ready
class Time
{
    // TODO: don't forget to add validation
    public int Hours   { get; set; }
    public int Minutes { get; set; }
    public int Seconds { get; set; }

    public override string ToString()
    {  
        return String.Format(
            "{0:00}:{1:00}:{2:00}",
            this.Hours, this.Minutes, this.Seconds);
    }
}

Or, why to bother: if you don't need to do any calculation with that information, just store it as String.

或者,为什么要麻烦:如果不需要对该信息进行任何计算,只需将其存储为字符串。

#4


16  

I say use a DateTime. If you don't need the date portion, just ignore it. If you need to display just the time to the user, output it formatted to the user like this:

使用DateTime。如果不需要日期部分,就忽略它。如果您需要只显示给用户的时间,则将它格式化为以下格式输出给用户:

DateTime.Now.ToString("t");  // outputs 10:00 PM

It seems like all the extra work of making a new class or even using a TimeSpan is unnecessary.

看起来创建一个新类甚至使用TimeSpan的所有额外工作都是不必要的。

#5


6  

I think Rubens' class is a good idea so thought to make an immutable sample of his Time class with basic validation.

我认为Rubens的类是一个好主意,所以我想用基本的验证来创建一个他的Time类的不变样本。

class Time
{
    public int Hours   { get; private set; }
    public int Minutes { get; private set; }
    public int Seconds { get; private set; }

    public Time(uint h, uint m, uint s)
    {
        if(h > 23 || m > 59 || s > 59)
        {
            throw new ArgumentException("Invalid time specified");
        }
        Hours = (int)h; Minutes = (int)m; Seconds = (int)s;
    }

    public Time(DateTime dt)
    {
        Hours = dt.Hour;
        Minutes = dt.Minute;
        Seconds = dt.Second;
    }

    public override string ToString()
    {  
        return String.Format(
            "{0:00}:{1:00}:{2:00}",
            this.Hours, this.Minutes, this.Seconds);
    }
}

#6


4  

In addition to Chibueze Opata:

除了Chibueze Opata之外:

class Time
{
    public int Hours   { get; private set; }
    public int Minutes { get; private set; }
    public int Seconds { get; private set; }

    public Time(uint h, uint m, uint s)
    {
        if(h > 23 || m > 59 || s > 59)
        {
            throw new ArgumentException("Invalid time specified");
        }
        Hours = (int)h; Minutes = (int)m; Seconds = (int)s;
    }

    public Time(DateTime dt)
    {
        Hours = dt.Hour;
        Minutes = dt.Minute;
        Seconds = dt.Second;
    }

    public override string ToString()
    {  
        return String.Format(
            "{0:00}:{1:00}:{2:00}",
            this.Hours, this.Minutes, this.Seconds);
    }

    public void AddHours(uint h)
    {
        this.Hours += (int)h;
    }

    public void AddMinutes(uint m)
    {
        this.Minutes += (int)m;
        while(this.Minutes > 59)
            this.Minutes -= 60;
            this.AddHours(1);
    }

    public void AddSeconds(uint s)
    {
        this.Seconds += (int)s;
        while(this.Seconds > 59)
            this.Seconds -= 60;
            this.AddMinutes(1);
    }
}

#7


1  

If you don't want to use a DateTime or TimeSpan, and just want to store the time of day, you could just store the seconds since midnight in an Int32, or (if you don't even want seconds) the minutes since midnight would fit into an Int16. It would be trivial to write the few methods required to access the Hour, Minute and Second from such a value.

如果您不想使用DateTime或TimeSpan,而只想存储一天的时间,那么您可以将午夜之后的秒存储为Int32,或者(如果您甚至不想要秒)午夜之后的分钟存储为Int16。编写从这样一个值访问小时、分钟和秒所需的几个方法是很简单的。

The only reason I can think of to avoid DateTime/TimeSpan would be if the size of the structure is critical.

我能想到的避免DateTime/TimeSpan的唯一原因是如果结构的大小是关键的。

(Of course, if you use a simple scheme like the above wrapped in a class, then it would also be trivial to replace the storage with a TimeSpan in future if you suddenly realise that would give you an advantage)

(当然,如果您使用一个简单的方案(如上面的包在类中的方案),那么如果您突然意识到这会给您带来优势,那么在将来用TimeSpan替换存储也很简单)

#1


108  

As others have said, you can use a DateTime and ignore the date, or use a TimeSpan. Personally I'm not keen on either of these solutions, as neither type really reflects the concept you're trying to represent - I regard the date/time types in .NET as somewhat on the sparse side which is one of the reasons I started Noda Time. In Noda Time, you can use the LocalTime type to represent a time of day.

正如其他人所说,您可以使用DateTime并忽略日期,或者使用TimeSpan。我个人并不喜欢这些解决方案,因为这两种类型都不能真正反映出你想要表达的概念——我把。net中的日期/时间类型看作是在稀疏的方面,这也是我开始野田时间的原因之一。在野田时间,你可以使用当地时间类型来代表一天中的一个时间。

One thing to consider: the time of day is not necessarily the length of time since midnight on the same day...

要考虑的一件事是:白天的时间不一定是同一天午夜之后的时间长度……

(As another aside, if you're also wanting to represent a closing time of a shop, you may find that you want to represent 24:00, i.e. the time at the end of the day. Most date/time APIs - including Noda Time - don't allow that to be represented as a time-of-day value.)

(另一方面,如果你也想代表一个商店的关门时间,你可能会发现你想代表24:00,也就是一天结束的时间。大多数日期/时间api(包括野田时间)都不允许将其表示为一天的时间值。

#2


129  

You can use timespan

您可以使用时间间隔

TimeSpan timeSpan = new TimeSpan(2, 14, 18);
Console.WriteLine(timeSpan.ToString());     // Displays "02:14:18".

[Edit]
Considering the other answers and the edit to the question, I would still use TimeSpan. No point in creating a new structure where an existing one from the framework suffice.
On these lines you would end up duplicating many native data types.

[编辑]考虑到其他的答案和编辑的问题,我仍然会使用TimeSpan。没有必要创建一个新结构,而框架中的现有结构就足够了。在这些行中,您将最终复制许多本机数据类型。

#3


26  

If that empty Date really bugs you, you can also to create a simpler Time structure:

如果那个空的日期真的让你烦恼,你也可以创建一个更简单的时间结构:

// more work is required to make this even close to production ready
class Time
{
    // TODO: don't forget to add validation
    public int Hours   { get; set; }
    public int Minutes { get; set; }
    public int Seconds { get; set; }

    public override string ToString()
    {  
        return String.Format(
            "{0:00}:{1:00}:{2:00}",
            this.Hours, this.Minutes, this.Seconds);
    }
}

Or, why to bother: if you don't need to do any calculation with that information, just store it as String.

或者,为什么要麻烦:如果不需要对该信息进行任何计算,只需将其存储为字符串。

#4


16  

I say use a DateTime. If you don't need the date portion, just ignore it. If you need to display just the time to the user, output it formatted to the user like this:

使用DateTime。如果不需要日期部分,就忽略它。如果您需要只显示给用户的时间,则将它格式化为以下格式输出给用户:

DateTime.Now.ToString("t");  // outputs 10:00 PM

It seems like all the extra work of making a new class or even using a TimeSpan is unnecessary.

看起来创建一个新类甚至使用TimeSpan的所有额外工作都是不必要的。

#5


6  

I think Rubens' class is a good idea so thought to make an immutable sample of his Time class with basic validation.

我认为Rubens的类是一个好主意,所以我想用基本的验证来创建一个他的Time类的不变样本。

class Time
{
    public int Hours   { get; private set; }
    public int Minutes { get; private set; }
    public int Seconds { get; private set; }

    public Time(uint h, uint m, uint s)
    {
        if(h > 23 || m > 59 || s > 59)
        {
            throw new ArgumentException("Invalid time specified");
        }
        Hours = (int)h; Minutes = (int)m; Seconds = (int)s;
    }

    public Time(DateTime dt)
    {
        Hours = dt.Hour;
        Minutes = dt.Minute;
        Seconds = dt.Second;
    }

    public override string ToString()
    {  
        return String.Format(
            "{0:00}:{1:00}:{2:00}",
            this.Hours, this.Minutes, this.Seconds);
    }
}

#6


4  

In addition to Chibueze Opata:

除了Chibueze Opata之外:

class Time
{
    public int Hours   { get; private set; }
    public int Minutes { get; private set; }
    public int Seconds { get; private set; }

    public Time(uint h, uint m, uint s)
    {
        if(h > 23 || m > 59 || s > 59)
        {
            throw new ArgumentException("Invalid time specified");
        }
        Hours = (int)h; Minutes = (int)m; Seconds = (int)s;
    }

    public Time(DateTime dt)
    {
        Hours = dt.Hour;
        Minutes = dt.Minute;
        Seconds = dt.Second;
    }

    public override string ToString()
    {  
        return String.Format(
            "{0:00}:{1:00}:{2:00}",
            this.Hours, this.Minutes, this.Seconds);
    }

    public void AddHours(uint h)
    {
        this.Hours += (int)h;
    }

    public void AddMinutes(uint m)
    {
        this.Minutes += (int)m;
        while(this.Minutes > 59)
            this.Minutes -= 60;
            this.AddHours(1);
    }

    public void AddSeconds(uint s)
    {
        this.Seconds += (int)s;
        while(this.Seconds > 59)
            this.Seconds -= 60;
            this.AddMinutes(1);
    }
}

#7


1  

If you don't want to use a DateTime or TimeSpan, and just want to store the time of day, you could just store the seconds since midnight in an Int32, or (if you don't even want seconds) the minutes since midnight would fit into an Int16. It would be trivial to write the few methods required to access the Hour, Minute and Second from such a value.

如果您不想使用DateTime或TimeSpan,而只想存储一天的时间,那么您可以将午夜之后的秒存储为Int32,或者(如果您甚至不想要秒)午夜之后的分钟存储为Int16。编写从这样一个值访问小时、分钟和秒所需的几个方法是很简单的。

The only reason I can think of to avoid DateTime/TimeSpan would be if the size of the structure is critical.

我能想到的避免DateTime/TimeSpan的唯一原因是如果结构的大小是关键的。

(Of course, if you use a simple scheme like the above wrapped in a class, then it would also be trivial to replace the storage with a TimeSpan in future if you suddenly realise that would give you an advantage)

(当然,如果您使用一个简单的方案(如上面的包在类中的方案),那么如果您突然意识到这会给您带来优势,那么在将来用TimeSpan替换存储也很简单)