【发布时间】:2014-07-11 13:42:47
【问题描述】:
好的,基本上我正在创建一个重新写入文件的文本文件格式化程序,我正在使用正则表达式来获取日期和时间值,现在我将它们四舍五入,然后当数据到达午夜时,日期增加一 -到目前为止一切正常,包括日期增加,除了它使用今天的日期作为开始日期而不是我文件中的日期。代码很长,但在这里...
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);
}
【问题讨论】:
-
如果您调用 AddHours(1) 并且结果通过午夜,则该天自动增加 1,如果您通过一个月的最后一天,该月将自动增加 1(您可以想象会发生什么如果月份是 12,则年份)