Search code examples
c#datetimeinteger

C# - Convert int to DateTime


I am dealing with the following problem. I have a bunch of int in 24h format without a colon. Something like this:

(HourMinute) meaning (Hour:Minute)
830          ->      08:30
1400         ->      14:00
245          ->      02:45
0            ->      00:00
2359         ->      23:59

etc. From this I want to create a DateTime. Something like this:

DateTime time = DateTime.Today + new TimeSpan(0, 0, 0);

So how to fill the TimeSpan? Or, in general, how to create a DateTime with today's date and int's time (00 seconds)?


Solution

  • Sounds like you just need to divide your integer by 100 to get hour part and calculate reminder by 100 to get minutes part?

    int i = 1430;
    var hours = i / 100; // 14 because of integer division
    var minutes = i % 100; // 30
    

    Then

    DateTime time = DateTime.Today + new TimeSpan(hours, minutes, 0);
    

    I have a bunch of int in 24h format without a colon.

    I have to mentioned that, this sentence is quite misleading. int (which is an alias for Int32) has no format. It has 32 bits which represent a number. All these 24 hour format concept belongs to string type (aka textual representation). If you new about programming, it is important to understand what is a value of a type and a textual representation of a type.

    EDIT:

    As an alternative, you can use Math.DivRem method as Dmitry mentioned in the comments which supports deconstructing declaration as introduced with C# 7.0 version like;

    Calculates the quotient of two numbers and also returns the remainder in an output parameter.

    int i = 1430;
    var (hours, minutes) = Math.DivRem(i, 100); 
    var time = DateTime.Today.AddHours(hours).AddMinutes(minutes);