3

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);
John Saunders
  • 160,644
  • 26
  • 247
  • 397
JoshF91
  • 99
  • 1
  • 3
  • 11

6 Answers6

4

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
}
Hans Kesting
  • 38,117
  • 9
  • 79
  • 111
  • I can see the logic but still having issues with the code, could you further assist with code ? – JoshF91 Jul 08 '14 at 13:20
3

In my case, I need to round it to lower hour, and I used this logic:

DateTime x = new DateTime();
x = x.Date.AddHours(x.Hour);
4b0
  • 21,981
  • 30
  • 95
  • 142
1

You can try one liner solution to convert your DateTime to nearest hour,

//Input DateTime
DateTime input = DateTime.ParseExact("28/05/2021 2:16 PM", "dd/MM/yyyy h:mm tt", CultureInfo.InvariantCulture);

//Ternary Operation
var output = input.Minute > 30  //Check if mins are greater than 30
       ? input.AddHours(1).AddMinutes(-input.Minute) //if yes, then add one hour and set mins to zero
       : input.AddMinutes(-input.Minute); //otherwise set mins to zero

Console.WriteLine(result.ToString());

Try Online: .NET Fiddle

Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44
0

Can you convert the string to a datetime?

Something like:

dateVariable = Convert.ToDateTime(dateString);
int hour = dateVariable.Hour;
int minute = dateVariable.Minute;

And then do the rounding.

user1666620
  • 4,800
  • 18
  • 27
0

Now as you have

            string[] str = split[1].Split('/');
            // create a new DateTime
            int minutes = int.Parse(str[1]);
            if(minutes >= 30)
                  hour = int.Parse(str[0]) + 1 // make sure if it 13 or 25 make it 1
                  minutes = 0 ;
                  sec = 0;
            else {
                 hour = int.Parse(str[0]);
                 minutes = 0 ;
                 sec = 0 ;
            }
            var myDate = new Date(Year, month , day , hour , minutes , sec);
Devesh
  • 4,500
  • 1
  • 17
  • 28
0

In C#

var Now = DateTime.Now;
var Nearest = Now.Date;
Nearest = Nearest.AddHours(Now.Hour + (Now.Minute >= 30 ? 1 : 0));

Now = Current time

Nearest = Rounded to the nearest hour

s k
  • 4,342
  • 3
  • 42
  • 61