提问人:Khayal Ads 提问时间:11/16/2023 更新时间:11/16/2023 访问量:82
从日期时间选取器和文本框 C 获取 dd/mm/yyyy 格式的日期,而不是 mm/dd/yyyyy#
Get date in dd/mm/yyyy format instead of mm/dd/yyyyy from Date time Picker and Textbox C#
问:
我尝试从日期时间选取器和文本框 C# 获取 dd/mm/yyyy 格式的日期,而不是 mm/dd/yyyyy 格式,但我面临“字符串未被识别为有效日期时间”消息错误”
我试过这段代码
if (tb_date.Text == "")
{
tb_date.Text = dtp_addingDebit.Value.ToString("dd/MM/yyyy");
}
else
{
tb_date.Text = Convert.ToDateTime(tb_date.Text).ToString("dd/MM/yyyy");
}
我使用带有插入存储过程的 If 条件的结果
AddingDebit_con.AddingNewDebit(int.Parse(combo_customers.SelectedValue.ToString()),tb_date.Text, Convert.ToInt32(tb_amount.Text));
AddingDebit_con是包含以下代码.cs文件
public void InsertCustomer(string customer_fullname, string customer_phone, string customer_address, string customer_date)
{
DAL.DataAccessLayer DAL = new DAL.DataAccessLayer();
DAL.Open();
SqlParameter[] param = new SqlParameter[4];
param[0] = new SqlParameter("@customer_fullname", SqlDbType.NVarChar); param[0].Value = customer_fullname;
param[1] = new SqlParameter("@customer_phone", SqlDbType.NVarChar); param[1].Value = customer_phone;
param[2] = new SqlParameter("@customer_address", SqlDbType.NVarChar); param[2].Value = customer_address;
param[3] = new SqlParameter("@customer_date", SqlDbType.Date); param[3].Value = customer_date;
DAL.ExcuteCommand("Inserting_Customers", param);
DAL.Close();
}
AddingNewDebit 是包含以下 Sql-server 代码的存储过程
ALTER proc [dbo].[Inserting_Customers]
@customer_fullname nvarchar(max),
@customer_phone nvarchar(max),
@customer_address nvarchar(max),
@customer_date date
AS
INSERT INTO Customers
([customer_fullname]
,[customer_phone]
,[customer_address]
,[customer_date]
)
VALUES
(@customer_fullname,
@customer_phone,
@customer_address ,
@customer_date
)
答:
0赞
Dmitry Bychenko
11/16/2023
#1
您正在尝试将值设置为:string
DateTime
// Note "string" type for "customer_date"
public void InsertCustomer(... string customer_date)
{
...
// MS SQL expects "DateTime" - SqlDbType.Date
param[3] = new SqlParameter("@customer_date", SqlDbType.Date);
// But it's given "string"
param[3].Value = customer_date;
...
}
我建议更改类型:customer_date
// customer_date is DateTime now
public void InsertCustomer(... DateTime customer_date)
{
...
}
当你想调用该方法时,你应该提供:DateTime
// Note absence of any "ToString()" here
InsertCustomer(..., myDateTimePicker.Value);
评论
0赞
Khayal Ads
11/16/2023
感谢您的帮助:)它有效,但日期格式仍然插入为 mm/dd/yyyy,我该如何修复它,我也希望用户能够在文本框中以 dd/mm/yyyy 格式写入日期
0赞
Dmitry Bychenko
11/16/2023
@Khayal广告:请注意,您可以有模棱两可的值: - 是 OR ?11/5/2023
5 November 2023
11 May 2023
0赞
Dmitry Bychenko
11/16/2023
@Khayal广告:如果你想从字符串中获取,请使用:DateTime
TryParse
if (DateTime.TryParse(myText, out var myDate)) { /* valid myDate*/} else {/* invalid input */}
0赞
Salem Gogah
11/16/2023
#2
确保控件 Format 属性已正确设置为使用自定义格式:
dtp_addingDebit.Format = dtp_addingDebit.Custom
然后,您可以通过以下方式设置所需的格式:
dtp_addingDebit.CustomFormat = "dd-MM-yyyy"
评论
customer_date
string
... string customer_date ...