将时间四舍五入到最接近的小时 [英] Rounding up a time to the nearest hour

查看:88
本文介绍了将时间四舍五入到最接近的小时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

返回的这个新值同时获取时间和日期值,但仅作为一个字符串,因此我然后使用拆分(如下所示)将两个值分开,现在拆分 [0] 是我的时间变量 (00/00/00 格式) - 我现在需要四舍五入到最接近的小时.我真的不知道该怎么做,有什么想法吗?

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

推荐答案

从字符串中获取该日期到 DateTime 结构中.例如,参见 TryParseExact 方法

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

然后您可以根据上一步中值的年/月/日/小时创建一个新的 DateTime 值,将分钟和秒部分设置为零(请参阅 此处 )

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 )

如果分钟或秒部分(您的第一个值)不为零,则添加一个小时,使用 .AddHours(1),它返回一个新的 DateTime 值.

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
}

这篇关于将时间四舍五入到最接近的小时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆