Reputation: 139
Ok basically I am creating a text file formatter which re - writes files, I am using regex to get the date and time values and now I am rounding them up and then when the data hits midnight the date is increased by one - everything works so far including the date increase apart from the fact it using todays date as the start date and not the date from my file. code is quite long but here it is...
line = Regex.Replace(line, @"\s+", ",");
string[] split = date1.Split(' ');
string inputime= split[0];
DateTime dt ;
System.Globalization.CultureInfo enUS = new System.Globalization.CultureInfo("en-US");
DateTime.TryParseExact(inputime, "HH:mm:ss", enUS, System.Globalization.DateTimeStyles.None, out dt);
DateTime rounded;
if (dt.Minute >= 30)
{
rounded = Round(dt, "up");
}
else
{
rounded = Round(dt, "down");
}
writer.WriteLine( rounded.ToString("dd/MM/yyyy") + "," + rounded.ToString("HH:mm:ss") + "," + line);
count1--;
line = Regex.Replace(line, @"\s+", ",");
}
}
}
writer.Close();
}
MessageBox.Show("Formatting Complete");
}
}
public static DateTime Round(DateTime dateTime, string direction)
{
var updated = dateTime.AddHours(1);
var updated1 = dateTime.AddDays(1);
switch (direction)
{
case "up":
if (dateTime.Hour == 00)
{
updated1.AddDays(dateTime.Day);
return new DateTime(updated1.Year, updated1.Month, updated1.Day, updated.Hour, 0, 0, dateTime.Kind);
}
else
{
return new DateTime(updated.Year, updated.Month, updated.Day, updated.Hour, 0, 0, dateTime.Kind);
}
case "down":
{
updated.AddHours(dateTime.Hour);
return new DateTime(updated.Year, updated.Month, updated.Day, updated.Hour, 0, 0, dateTime.Kind);
}
}
return (dateTime);
}
Upvotes: 0
Views: 138
Reputation: 60503
Your code should really be corrected on other points, but for your question :
On this line
DateTime.TryParseExact(inputime, "HH:mm:ss", enUS, System.Globalization.DateTimeStyles.None, out dt);
you're creating a DateTime
with hours minutes and seconds.
If you don't provide year, month, day, the current day will be taken.
So you need to parse with year, month, day also to get these values.
Upvotes: 2
Reputation: 63742
Read the time into a TimeSpan
(using e.g. TimeSpan.Parse
), and use the date of the file as the start value. To get the full date and time you can then simply do
currentDate + currentTime
Also, be careful about midnight. IIRC some cultures count midnight as part of the previous day and others might have it part of the next day.
Upvotes: 0