将时间四舍五入到最近的小时

3

好的,基本上我有一个程序,它通过各种条件重新编写文本文件并对其进行格式化。其中一个条件是,我的原始文本文件中的日期和时间值需要从其当前位置移除并移到我创建的新列中,这可以使用以下代码完成。我使用正则表达式查找日期和时间格式,然后将其从当前位置删除并将该值存储在变量中,以便稍后使用...

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;
}

这个新的返回值包含了时间和日期,但只作为一个字符串返回,因此我使用了split(如下所示)将两个值分开,现在split [0] 是我的时间变量(00/00/00格式),我现在需要将其四舍五入到最近的小时。我真的不知道该怎么做,有什么建议吗?

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

您向下舍入的标准是什么? - Mark Hall
只需找到最接近的分钟数,即可确定时间,例如10:35:10将是11:00:00。 - JoshF91
6个回答

4
从字符串中获取日期并将其转换为DateTime结构。例如,可以参考TryParseExact方法。
然后,您可以创建一个新的DateTime值,基于上一步的年/月/日/小时值,将分钟和秒部分设置为零(请参见here)。
如果第一个值的分钟或秒部分不为零,则添加一小时,使用.AddHours(1),它返回一个新的DateTime值。 编辑
一些示例代码:
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
}

我能理解逻辑,但代码仍然有问题,你能提供更进一步的帮助吗? - JoshF91

3
在我的情况下,我需要将它舍入到较低的小时数,并使用以下逻辑:
DateTime x = new DateTime();
x = x.Date.AddHours(x.Hour);

1
你可以尝试使用一行代码将你的转换为最近的小时。
//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());

尝试在线:.NET Fiddle

0

在C#中

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

Now = 当前时间

Nearest = 四舍五入到最近的小时


请在您的答案中至少添加一个简短的解释。 - Quimby

0
你能把字符串转换成日期时间吗?
类似这样:
dateVariable = Convert.ToDateTime(dateString);
int hour = dateVariable.Hour;
int minute = dateVariable.Minute;

然后进行四舍五入。


0

现在,既然你已经

            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);

为什么不从 DateTime.Parse/ParseExact 开始,然后进行舍入逻辑呢? - Yahya

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接