计算日期差异 [英] Calculating date difference

查看:98
本文介绍了计算日期差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 String was not recognized as a valid DateTime.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.FormatException: String was not recognized as a valid DateTime.

Source Error:


Line 132:        protected void Button4_Click(object sender, EventArgs e)
Line 133:        {
Line 134:            DateTime a = Convert.ToDateTime(TextBox13.Text);
Line 135:            DateTime b = Convert.ToDateTime(TextBox14.Text);
Line 136:            string c = (b - a).TotalDays.ToString();





我的尝试:



DateTime a = Convert.ToDateTime(TextBox13.Text);

DateTime b = Convert.ToDateTime(TextBox14.Text);

string c =(b - a)。 TotalDays.ToString();

TextBox15.Text = c.ToString();



What I have tried:

DateTime a = Convert.ToDateTime(TextBox13.Text);
DateTime b = Convert.ToDateTime(TextBox14.Text);
string c = (b - a).TotalDays.ToString();
TextBox15.Text = c.ToString();

推荐答案

TryParse ParseExact 。按照这个很棒的答案 - 字符串未被识别为有效DateTime。 [ ^ ]
TryParse or ParseExact should be used. Follow this awesome answer - String was not recognized as a valid DateTime.[^]


string c = (b - a).TotalDays.ToString();



当您不确定发生了什么时,这样的语句不是很有用。使用适当的中间类型,以便您可以使用调试器逐步执行代码,并在每个阶段查看结果。类似于:


Statements like that are not very useful when you are not sure of what is happening. Use proper intermediate types so you can step through the code with your debugger and see the results at each stage. Something like:

TimeSpan c = b - a;
int days = c.TotalDays;
string str = days.ToString();


首先转换值到datetime,然后将它减去并在Timespan中返回

First you Converted the values to datetime, then just substract it and return it in Timespan
DateTime a = Convert.ToDateTime(TextBox13.Text);
DateTime b = Convert.ToDateTime(TextBox14.Text);
TimeSpan ts1 = b.Subtract(a);

</pre>
Hope it gives you the exact result..


这篇关于计算日期差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆