使用c#计算两个日期之间的差异

时间:2016-09-08 07:02:05

标签: c# asp.net

我试图计算两个日期之间的差异,我的代码在下面给出

DateTime daterenew = DateTime.Parse(drow.ItemArray.GetValue(16).ToString()); //18/01/2017
        DateTime datecurrent = DateTime.Parse(DateTime.Now.ToString("dd/MM/yyyy"));
        renewstatuslbl.Text = ((daterenew - datecurrent).Days) + " Day(s) remains";

但我收到错误

  

" String未被识别为有效的DateTime。"

4 个答案:

答案 0 :(得分:0)

假设您的drow.ItemArray.GetValue(16).ToString()格式始终为dd/MM/yyyy。使用ParseExact

        DateTime daterenew = DateTime.ParseExact(drow.ItemArray.GetValue(16).ToString(), "dd/MM/yyyy", null); //18/01/2017
        //DateTime datecurrent = DateTime.Parse(DateTime.Now.ToString("dd/MM/yyyy"));
        DateTime datecurrent = DateTime.Now;
        renewstatuslbl.Text = ((daterenew - datecurrent).Days) + " Day(s) remains";

答案 1 :(得分:0)

我会简化:

'choice_attr' => function($val, $key) {
   return ['data-object' => json_encode($val)];
},

注意,var daterenew = DateTime.ParseExact("18/01/2017", "dd/MM/yyyy", CultureInfo.InvariantCulture); var res = ((daterenew - DateTime.Today).Days) + " Day(s) remains"; != DateTime.Now

答案 2 :(得分:0)

日期的格式,导致错误。 18/01/2017 https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx

示例我使用了"yyyy/MM/dd"

//DateTime daterenew = DateTime.Parse("18/01/2017"); //18/01/2017
DateTime daterenew = DateTime.Parse("2017.01.18"); //18/01/2017
DateTime datecurrent = DateTime.Parse(DateTime.Now.ToString("dd/MM/yyyy"));
object renewstatuslbl = ((daterenew - datecurrent).Days) + " Day(s) remains";

因此,我认为您可以在插入drow.ItemArray

之前更改值的第一个字符串日期格式

答案 3 :(得分:0)

尝试这样的事情

string dateString = drow.ItemArray.GetValue(16).ToString();
DateTime daterenew = DateTime.ParseExact(dateString, "dd/MM/yyyy", CultureInfo.InvariantCulture); 

renewstatuslbl.Text = string.Format("{0} Day(s) remains", (daterenew - DateTime.Now).TotalDays);

想法在ParseExact中,您可以在drow.ItemArray中设置日期的格式 另请参阅TotalDays