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

前端 未结 15 2151
面向向阳花
面向向阳花 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:31

    What I think you're asking for is a variable that will store minutes as a number. This can be done with the varying types of integer variable:

    SELECT 9823754987598 AS MinutesInput
    

    Then, in your program you could simply view this in the form you'd like by calculating:

    long MinutesInAnHour = 60;
    
    long MinutesInADay = MinutesInAnHour * 24;
    
    long MinutesInAWeek = MinutesInADay * 7;
    
    
    long MinutesCalc = long.Parse(rdr["MinutesInput"].toString()); //BigInt converts to long. rdr is an SqlDataReader.   
    
    
    long Weeks = MinutesCalc / MinutesInAWeek;
    
    MinutesCalc -= Weeks * MinutesInAWeek;
    
    
    long Days = MinutesCalc / MinutesInADay;
    
    MinutesCalc -= Days * MinutesInADay;
    
    
    long Hours = MinutesCalc / MinutesInAnHour;
    
    MinutesCalc -= Hours * MinutesInAnHour;
    
    
    long Minutes = MinutesCalc;
    

    An issue arises where you request for efficiency to be used. But, if you're short for time then just use a nullable BigInt to store your minutes value.

    A value of null means that the time hasn't been recorded yet.

    Now, I will explain in the form of a round-trip to outer-space.

    Unfortunately, a table column will only store a single type. Therefore, you will need to create a new table for each type as it is required.

    For example:

    • If MinutesInput = 0..255 then use TinyInt (Convert as described above).

    • If MinutesInput = 256..131071 then use SmallInt (Note: SmallInt's min value is -32,768. Therefore, negate and add 32768 when storing and retrieving value to utilise full range before converting as above).

    • If MinutesInput = 131072..8589934591 then use Int (Note: Negate and add 2147483648 as necessary).

    • If MinutesInput = 8589934592..36893488147419103231 then use BigInt (Note: Add and negate 9223372036854775808 as necessary).

    • If MinutesInput > 36893488147419103231 then I'd personally use VARCHAR(X) increasing X as necessary since a char is a byte. I shall have to revisit this answer at a later date to describe this in full (or maybe a fellow stackoverflowee can finish this answer).

    Since each value will undoubtedly require a unique key, the efficiency of the database will only be apparent if the range of the values stored are a good mix between very small (close to 0 minutes) and very high (Greater than 8589934591).

    Until the values being stored actually reach a number greater than 36893488147419103231 then you might as well have a single BigInt column to represent your minutes, as you won't need to waste an Int on a unique identifier and another int to store the minutes value.

提交回复
热议问题