Best way to store time (hh:mm) in a database

前端 未结 15 2121
面向向阳花
面向向阳花 2020-11-29 18:58

I want to store times in a database table but only need to store the hours and minutes. I know I could just use DATETIME and ignore the other components of the date, but wha

15条回答
  •  既然无缘
    2020-11-29 19:25

    Store the ticks as a long/bigint, which are currently measured in milliseconds. The updated value can be found by looking at the TimeSpan.TicksPerSecond value.

    Most databases have a DateTime type that automatically stores the time as ticks behind the scenes, but in the case of some databases e.g. SqlLite, storing ticks can be a way to store the date.

    Most languages allow the easy conversion from TicksTimeSpanTicks.

    Example

    In C# the code would be:

    long TimeAsTicks = TimeAsTimeSpan.Ticks;
    
    TimeAsTimeSpan = TimeSpan.FromTicks(TimeAsTicks);
    

    Be aware though, because in the case of SqlLite, which only offers a small number of different types, which are; INT, REAL and VARCHAR It will be necessary to store the number of ticks as a string or two INT cells combined. This is, because an INT is a 32bit signed number whereas BIGINT is a 64bit signed number.

    Note

    My personal preference however, would be to store the date and time as an ISO8601 string.

提交回复
热议问题