【发布时间】:2016-10-18 08:12:02
【问题描述】:
我很难想出一个干净的解决方案来解决以下问题。 我需要根据月度分辨率找到时间间隔(日期从/日期到)之间给定日期的索引。
例子:
date format = yyyy-MM-dd
timeIntervalFrom = 2016-02-01
timeIntervalTo = 2017-03-01
searchDate = 2017-01-01
这里的索引是 11。
我想出的唯一方法是蛮力搜索,但我觉得有一种更简洁的方法可以通过一些数学来解决这个问题。
var index = 0;
while (timeIntervalFrom < timeIntervalTo)
{
if (timeIntervalFrom == searchDate)
break;
index++;
timeIntervalFrom = timeIntervalFrom.AddMonths(1);
}
任何建议将不胜感激!
编辑:
这是一个可编译的解决方案,它表明当时间间隔因月份长度不同而变宽时,使用@Pikoh 解决方案会停止正常工作,因此这不是一个可行的解决方案。
using System;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
int endYear = 2022;
var index1 = FindIndex1(new DateTime(2016, 1, 1), new DateTime(endYear, 3, 1), new DateTime(endYear, 2, 1));
var index2 = FindIndex2(new DateTime(2016, 1, 1), new DateTime(endYear, 3, 1), new DateTime(endYear, 2, 1));
Console.Out.WriteLine($"FindIndex1: {index1}, FindIndex2: {index2}, Result: {(index1 == index2 ? "OK" : "FAIL")}");
}
private static int FindIndex1(DateTime timeIntervalFrom, DateTime timeIntervalTo, DateTime searchDate)
{
var index = 0;
while (timeIntervalFrom < timeIntervalTo)
{
if (timeIntervalFrom == searchDate)
break;
index++;
timeIntervalFrom = timeIntervalFrom.AddMonths(1);
}
return index;
}
private static int FindIndex2(DateTime timeIntervalFrom, DateTime timeIntervalTo, DateTime searchDate)
{
return (searchDate - timeIntervalFrom).Days / 30;
}
}
}
编辑2:
我已经设法找到正确的解决方案阅读提供的链接@Charles Mager 提供。所以在某种程度上@Pikoh 非常接近。非常感谢你们!
private static int FindIndex3(DateTime timeIntervalFrom, DateTime searchDate)
{
return (int) (searchDate.Subtract(timeIntervalFrom).Days / (365.2425 / 12));
}
【问题讨论】:
-
听起来很像Difference in months between two dates 和
searchDate.Subtract(timeIntervalFrom)。 -
索引表示自日期以来的月数?如果是这样,请尝试
var index = (searchDate - timeIntervalFrom).Days/30; -
我不明白为什么你有三个值。你没有在你的例子中使用
searchDate -
为什么说我的解决方案不起作用?如果我的计算没问题,从 2016 年 1 月到 2022 年 3 月,有 75 个月……您认为正确的结果应该是什么?