返回月份&来自TimeSpan asp.net的日子

时间:2017-11-27 12:57:02

标签: c# asp.net datetime timespan

我想从Datetime创建的Seconds,Minuites,Hours,Days,Months和Years返回。

我写了这段代码

public static string ReturnCreatedSince(DateTime createdOn)
    {
        //Get current datetime
        var today = DateTime.Now;

        // Get days in current month
        var daysInMonth = DateTime.DaysInMonth(today.Year, today.Month);

        double seconds = 60;
        double minutes = seconds * 60;
        double hours = minutes * 60;
        double days = hours * 24;
        //double weeks = days * 7;
        double months = days * daysInMonth;
        double years = months * 12;

        //Convert created datetime to seconds
        var datetimeInSeconds = (today - createdOn).TotalSeconds;

        var createdSince = string.Empty;

        if (datetimeInSeconds <= seconds) //seconds between 1 to 60
        {
            return TimeSpan.FromSeconds(datetimeInSeconds).Seconds.ToString() + " sec";
        }
        else if (datetimeInSeconds <= minutes)// Minuites between 1 to 60
        {
            return TimeSpan.FromSeconds(datetimeInSeconds).Minutes.ToString() + " mins";
        }
        else if (datetimeInSeconds <= hours)// Hours between 1 to 24
        {
            return TimeSpan.FromSeconds(datetimeInSeconds).Hours.ToString() + " hrs";                
        }
        else if (datetimeInSeconds <= days)// Days between 1 to 24
        {
            return TimeSpan.FromSeconds(datetimeInSeconds).Days.ToString() + " jrs";
        }           
        else if (datetimeInSeconds <= months)// Months between 1 to 24
        {
           return (datetimeInSeconds / months).ToString() + " m";
        }
        else if (datetimeInSeconds <= years)// Years between 1 to 12 
        {
            return (datetimeInSeconds / years).ToString() + " yrs";
        }
        else
        {
            return createdOn.ToShortDateString();
        }
    }

我使用以下值测试了代码

已修改

对于给定的日期时间

如果秒数小于60,那么它应该以秒为单位返回值。 如果秒数小于60且小于(60 * 60)秒,那么它应该以分钟为单位返回值,同样适用于小时,天数和年份

现在我有了这个约会"createdOn": "2017-10-16T14:41:16.557"并返回41天而不是预期的1个月。

我该如何解决呢?

1 个答案:

答案 0 :(得分:2)

@Tarik解决方案几个月会为您提供startDate和endDate之间的总月数。

要获取最后剩余的月份,请包含以下while循环语句。

DateTime startDate = new DateTime(2003, 1, 1);
DateTime endDate = new DateTime(2007, 12, 1);
int nbYears = endDate.Year - startDate.Year;
int nbMonths = ((endDate.Year - startDate.Year) * 12) + endDate.Month - startDate.Month;
while (nbMonths > 12)
{
    nbMonths = nbMonths % 12;
}
Console.WriteLine($"{nbYears} year(s) and {nbMonths} month(s)");

没有while循环,它将打印:4年和59个月 使用while循环,它可以打印:4年和11个月