【问题标题】:change a number of days to date更改迄今为止的天数
【发布时间】:2015-08-06 21:35:07
【问题描述】:

如何使用 C# 中的 DateTime 类将天数更改为(年、月和日) 。实际上我想用生日来计算确切的出生日期。 ?年?月....?秒。

我的代码:

DateTime a = new DateTime(1993, 6, 10, 0, 0, 0);
            DateTime now = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour
                ,DateTime.Now.Minute,DateTime.Now.Second);
            TimeSpan b = now - a;
            int c = b.Days;

【问题讨论】:

    标签: c# datetime timespan


    【解决方案1】:

    您可以使用NodaTime

    var period = NodaTime.Period.Between(
                    new NodaTime.LocalDateTime(1993, 6, 10, 0, 0), 
                    NodaTime.LocalDateTime.FromDateTime(DateTime.Now) );
    
    Console.WriteLine("{0} {1} {2} {3} {4}",period.Years,period.Months,period.Days,
                                            period.Hours,period.Minutes);
    

    【讨论】:

      【解决方案2】:

      我没有看到任何简单的功能。即无法使用简单的 DateTime 函数来做到这一点。但是,如果我将它放入代码中,它看起来像这样:

      DateTime birthday = new DateTime(1993, 6, 10);
      DateTime current;
      DateTime nowComparison = DateTime.Now;
      int years = nowComparison.Year - birthday.Year;
      if (nowComparison < birthday.AddYears(years))
          years -= 1;
      current = birthday.AddYears(years); // current is less than a year ago.
      
      int months;
      if(current.Year != nowComparison.Year)
      {
          months = nowComparison.Month + (12 - current.Month);
      }
      else
      {
          months = nowComparison.Month - current.Month;
      }
      if (nowComparison < current.AddMonths(months))
          months -= 1;
      current = current.AddMonths(months); // current is less than a month ago.
      
      int days = nowComparison.Subtract(current).Days;
      current = current.AddDays(days); // current is less than a day ago.
      
      int hours = nowComparison.Subtract(current).Hours;
      current = current.AddHours(hours); // current is less than an hour ago.
      
      int minutes = nowComparison.Subtract(current).Minutes;
      current = current.AddMinutes(minutes); // current is less than a minute ago.
      
      int seconds = nowComparison.Subtract(current).Seconds;
      current = current.AddSeconds(seconds); // current is less than a second ago.
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-01-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多