JCl*_*ill 5 c# sql-server datetime timestamp
我需要一些帮助才能将2个日期时间拆分为它们之间的小时间隔.
这与"付费"数据有关,因此需要非常准确.我需要使用clockin和clockout,并将它们分成小时间隔.
例:
clockin = 5/25/2011 1:40:56 PM
clockout = 5/25/2011 6:22:12 PM
我需要看起来像:
2011年5月25日下午1:40:56
5/25/2011 2:00:00 PM
5/25/2011 3:00:00 PM
5/25/2011 4:00:00 PM
5/25/2011 5:00:00 PM
5/25/2011 6:00:00 PM
5/25/2011 6:22:12 PM
然后,我计划在"差异"表格中检查这些时间,看看他们应该有一个新的付费代码.但我稍后会担心付费代码.
什么帮助分裂时代?喜欢C#,但我也可以访问MSSQL2000(这是我们拉原始时间的地方)
Mar*_*son 11
这样的事怎么样?
static IEnumerable<DateTime> GetWorkingHourIntervals(DateTime clockIn, DateTime clockOut)
{
yield return clockIn;
DateTime d = new DateTime(clockIn.Year, clockIn.Month, clockIn.Day, clockIn.Hour, 0, 0, clockIn.Kind).AddHours(1);
while (d < clockOut)
{
yield return d;
d = d.AddHours(1);
}
yield return clockOut;
}
Run Code Online (Sandbox Code Playgroud)
这使用迭代器块,但可以很容易地重写它以返回列表.
使用示例:
static void Main(string[] args)
{
var clockIn = new DateTime(2011, 5, 25, 13, 40, 56);
var clockOut = new DateTime(2011, 5, 25, 18, 22, 12);
var hours = GetWorkingHourIntervals(clockIn, clockOut);
foreach (var h in hours)
Console.WriteLine(h);
Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)
输出:
2011-05-25 13:40:56 2011-05-25 14:00:00 2011-05-25 15:00:00 2011-05-25 16:00:00 2011-05-25 17:00:00 2011-05-25 18:00:00 2011-05-25 18:22:12
更新:LukeH非常聪明地建议你也应该复制DateTimeKind.如果您计划稍后将日期时间转换为本地时间,那么这确实是一个明智之举.
var hours = new List<DateTime>();
hours.Add(clockin);
var next = new DateTime(clockin.Year, clockin.Month, clockin.Day,
clockin.Hour, 0, 0, clockin.Kind);
while ((next = next.AddHours(1)) < clockout)
{
hours.Add(next);
}
hours.Add(clockout);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2532 次 |
| 最近记录: |