C# 如何在c中解析输出为“两个月”的日期时间范围?
是否存在从两个日期返回如下格式的c日期解析器:C# 如何在c中解析输出为“两个月”的日期时间范围?,c#,parsing,datetime,formatting,intervals,C#,Parsing,Datetime,Formatting,Intervals,是否存在从两个日期返回如下格式的c日期解析器: - two days - one month - two years 或者类似的 例如: 日期时间1=10/11/2013 日期时间2=11/12/2013 产量:一个月零一天 我已经搜索过了,但没有找到关于这种解析器的任何信息。您应该使用TimeSpan类型的对象,它是通过从另一个DateTime中减去一个DateTime得到的 然后您只需要格式化输出字符串 DateTime dateTime1 = new DateTime(2000, 01,
- two days
- one month
- two years
或者类似的
例如:
日期时间1=10/11/2013
日期时间2=11/12/2013
产量:一个月零一天
我已经搜索过了,但没有找到关于这种解析器的任何信息。您应该使用TimeSpan类型的对象,它是通过从另一个DateTime中减去一个DateTime得到的 然后您只需要格式化输出字符串
DateTime dateTime1 = new DateTime(2000, 01, 01, 0, 0, 0);
DateTime dateTime2 = new DateTime(2001, 02, 02, 10, 10, 10);
TimeSpan timeSpan1 = dateTime1 - dateTime2;
DateTime dateTime3 = new DateTime(timeSpan1.Ticks);
string string1 =
dateTime3.Day + " days" +
dateTime3.Month + " months" +
dateTime3.Year + " years";
在正确的轨道上,您仍然需要计算您真正想要的值,一周中的几天,一个月中的几天等等。在测量两个日期之间的间隔,并以1Y 2M 3D的形式将结果作为字符串给出时,自然的假设是使用.NET TimeSpan类。但这一假设并不成立,因为TimeSpan只测量天、小时、分钟和秒,而不提供任何有关已用月数的信息。或者几年。这意味着你必须深入研究日历才能知道一个月有多少天,等等
一个可以用来解决这个问题的辅助方法是
private static String Interval(DateTime start, DateTime end)
{
if (end <= start)
{
throw new Exception("Invalid interval");
}
int days = 0;
int months = 0;
int years = 0;
DateTime temp = start;
while (start.AddYears(years) <= end)
{
++years;
}
--years;
temp = temp.AddYears(years);
while (temp.AddMonths(months) <= end)
{
++months;
}
--months;
temp = temp.AddMonths(months);
while (temp.AddDays(days) <= end)
{
++days;
}
--days;
StringBuilder result = new StringBuilder();
if (years > 0)
{
result.AppendFormat("{0}Y ", years);
}
if (months > 0)
{
result.AppendFormat("{0}M ", months);
}
if (days > 0)
{
result.AppendFormat("{0}D", days);
}
return result.ToString();
}
等等
您可以使用相同的技术将间隔分解为分钟和秒。您可以通过添加另一个变量并在其上循环,将周引入该方法
while (temp.AddDays(weeks*7) <= end)
{
++weeks;
}
--weeks;
temp = temp.AddDays(weeks*7);
很抱歉格式设置不好,代码格式化程序似乎已经过时了
特里瓦:传奇人物乔恩·斯基特尝试回答这个问题,但后来写道他没有时间完成答案 解析?或者,您是指这种格式的输出?我是指用户在两个DateTimePickers中选择的两个DateTime对象的输出您是从字符串转换为DateTime对象-解析-还是从DateTime转换为字符串-输出格式?为什么不使用解释问题的示例输入和输出更新您的问题。如果没有示例,则不清楚您试图执行的操作可能重复的TimeSpan无法计算周/月,因为月份中的天数不一致,因此无法计算正确的月数,新的DateTimeSpan1.Ticks;使用1/1/0001 12:00:00 AM作为其计算的起点。如果您的开始日期不是1月1日,或者您超过了闰年日期,则数字可能会从测试2月1日到3月1日进行检查。编辑:您的示例抛出ArgumentOutOfRangeException,您需要执行timeSpan1=dateTime2-dateTime1;相反
while (temp.AddDays(weeks*7) <= end)
{
++weeks;
}
--weeks;
temp = temp.AddDays(weeks*7);