Search code examples
c#variablestimesplitrounding

Rounding up a time to the nearest hour


ok basically I have a program that is re-writing text files and formatting them through various conditions, one of the conditions is that the date and time values in my original text file needs to be removed from its current location and moved into a new column I have created, this is done with the code below. I used a regex to find the date and time format and then remove it from its current location and store the value in a variable that I can use later...

if (line.Contains(date))
{
    string pattern = @"(\d{2}:\d{2}:\d{2}\s?\d{2}/\d{2}/\d{4})";
    string input = line;
    string replacement = "";
    Regex rgx = new Regex(pattern);
    date1 = rgx.Match(input).ToString();
    string result = rgx.Replace(input, replacement);
    line = result;
}

This new value that is returned gets both the time and date values but only as one string, so I then used a split (shown below) to get the two values separate, now split[0] is my time variable (00/00/00 format) - which I now need to round up to the nearest hour. I am really not sure how to go about this, any ideas ?

string[] split = date1.Split(' ');                
writer.WriteLine(split[0] + "\t" + split[1] + "\t" + line);

Solution

  • Get that date from the string into a DateTime struct. See for example the TryParseExact method

    Then you can create a new DateTime value, based on year/month/day/hour of the value from the previous step, setting the minute and second parts to zero (see here )

    Add one hour if the minutes or seconds part (of your first value) is not zero, using .AddHours(1), which returns a new DateTime value.

    EDIT
    Some sample code:

    string inputdate = "2:56:30 8/7/2014";
    
    DateTime dt;
    System.Globalization.CultureInfo enUS = new System.Globalization.CultureInfo("en-US");
    
    if (DateTime.TryParseExact(inputdate, "H:m:s d/M/yyyy", // hours:minutes:seconds day/month/year
        enUS, System.Globalization.DateTimeStyles.None, out dt))
    {
      // 'dt' contains the parsed date: "8-7-2014 02:56:30"
      DateTime rounded = new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, 0, 0);
      if (dt.Minute > 0 || dt.Second > 0) // or just check dt.Minute >= 30 for regular rounding
        rounded = rounded.AddHours(1);
    
      // 'rounded' now contains the date rounded up: "8-7-2014 03:00:00"
    }
    else
    {
      // not a correct date
    }