Skip to main content
 首页 » 编程设计

c#之指定格式时的日期时间转换问题

2024年02月13日15zhenyulu

我的代码抛出一个错误:

When converting string to datetime, parse the string to take the date before putting each variable into datetime object.

代码:

我需要在文本框中显示默认值,即当前日期。

txtIssuingDate.Text = DateTime.Now.ToString("dd/MM/yyyy");  

然后我也需要在没有指定格式的情况下将其保存在数据库中

ComposedLetterBizz CompLetterBizz = new ComposedLetterBizz(Convert.ToInt32(txtName.Text),   
    Convert.ToInt32(HiddenFieldComplaintID.Value),   
    txtLetterNo.Text,   
    txtDispatchNo.Text,   
    txtSubject.Text,   
    Convert.ToInt16(ddlDepartments.SelectedValue),   
    Convert.ToInt16(ddlDesignations.SelectedValue),   
    Convert.ToDateTime(txtIssuingDate.Text),   
    Convert.ToDateTime(txtDeadLine.Text)); 

请您参考如下方法:

将 DateTime.Parse 与 CultureInfo.InvariantCulture 一起使用,以防您的文化不使用 / 作为日期分隔符:

所以代替

Convert.ToDateTime(txtIssuingDate.Text) 

它使用你当前文化的日期分隔符,这个

DateTime.Parse(txtIssuingDate.Text, CultureInfo.InvariantCulture) 

但是当您将日期分配给 TextBox.Text 时,您也应该这样做:

txtIssuingDate.Text = DateTime.Now.ToString(CultureInfo.InvariantCulture); 

The "/" Custom Format Specifier