【问题标题】:How to get months difference between two dates using datediff in c#如何在 c# 中使用 datediff 获取两个日期之间的月差
【发布时间】:2019-09-11 08:09:26
【问题描述】:

我有两个日期字段,我需要计算这两个日期之间的月差,我该怎么做。下面是我的公式

(start.Year * 12 + start.Month) - (end.Year * 12 + end.Month);

预期结果

Start Date      End Date      Need to get output as
08/28/2019      09/02/2019            1
06/01/2019      09/02/2019            4
01/02/2019      03/02/2019            3
01/02/2019      03/05/2019            3

【问题讨论】:

  • 您的标题说您想在 C# 中执行此操作,但您已标记 jQuery - 那么它是什么?无论哪种情况,我都 100% 确定这个问题已经有了答案
  • 我已经尝试过了,但我没有得到预期的结果
  • 来自hereFor example, should dates like July 5, 2009 and August 4, 2009 yield one month or zero months difference? If you say it should yield one, then what about July 31, 2009 and August 1, 2009? Is that a month? Is it simply the difference of the Month values for the dates, or is it more related to an actual span of time?。这是非常重要的!
  • 你应该告诉我们你得到了什么输出。它应该是结束开始,而不是开始结束。

标签: datediff


【解决方案1】:

虽然您没有告诉我们计算您所追求的结果的规则是什么,但看起来您需要检查月份中的日期并在结束时添加一个相同或更晚:

using System;
using System.Globalization;
using System.Linq;

namespace ConsoleApp1
{
    class Program
    {
        class DatePair
        {
            public DateTime Start { get; set; }
            public DateTime End { get; set; }

            public DatePair(string s)
            {
                var ci = new CultureInfo("en-US");
                var parts = s.Split(",".ToCharArray());
                this.Start = DateTime.Parse(parts[0], ci);
                this.End = DateTime.Parse(parts[1], ci);
            }
        }

        static void Main(string[] args)
        {
            string dats = "08/28/2019,09/02/2019;06/01/2019,09/02/2019;01/02/2019,03/02/2019;01/02/2019,03/05/2019";
            var dates = dats.Split(";".ToCharArray()).Select(p => new DatePair(p));

            foreach (DatePair d in dates)
            {
                var x = d.End.Month - d.Start.Month;
                if (d.End.Day >= d.Start.Day) { x += 1; }
                Console.WriteLine(d.Start.ToString("yyyy-MM-dd") + " " + d.End.ToString("yyyy-MM-dd") + " " + x.ToString());

            }

            Console.ReadLine();

        }
    }
}

输出:

2019-08-28 2019-09-02 1
2019-06-01 2019-09-02 4
2019-01-02 2019-03-02 3
2019-01-02 2019-03-05 3

我没有在计算中包括年份,因为没有示例日期。

【讨论】:

    猜你喜欢
    • 2013-07-23
    • 2016-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    相关资源
    最近更新 更多