如何平均日期

时间:2016-08-08 02:22:35

标签: c# c#-4.0

最终日期值应类似20080405,但显示为20080229

public class Program
{
    public static void Main(string[] args)
    {
         DateTime dt1 = new DateTime(dt);

        List<DateTime> arryDates = new List<DateTime>();

         Decimal[] avgdatetimevalues = { 20080229, 20080304, 20080304, 20080224 };//(Sum = 80321061; sum/4 = 20080265)
         // the final date value should be something like 20080405 but this is showing as 20080229


        try
        {
            for(int i = 0; i< avgdatetimevalues.Length; i++)
            {
                arryDates.Add(ValueToDate(avgdatetimevalues[i]));
            }
            var cnt = arryDates.Count();
            double temp = 0D;
            if (cnt > 0)
            {
                for (int i = 0; i < cnt; i++)
                {
                    temp += ( arryDates[i].Ticks / (double)cnt);
                }
                var average = new DateTime((long)temp);

            }

        }
        catch (Exception ex)
        {
            throw;
        }


    }
    public static DateTime ValueToDate(decimal dt)
    {
        DateTime dates;
        DateTime.TryParseExact(dt.ToString(), "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out dates);
        return dates;
    }
}

1 个答案:

答案 0 :(得分:-1)

你如何包含这些数据?

您可以在List中包含它们,如下所示:

List<decimal> values = new List<decimal> { 20080229, 20080304, 20080304, 20080224 };

然后使用这样的东西:

Console.WriteLine(values.Average());

获取列表中所有数据的平均值。 这很简单:)