日期时间转换C# [英] DateTime Conversion C#
本文介绍了日期时间转换C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在转换由用户以''MM-dd-yyyy''
格式输入的日期时遇到问题.
我用了
Hi,
I have a problem while converting date which is entered by user in format of ''MM-dd-yyyy''
.
I used
dt = convert.todatetime(txt_date.text);
但由于无法将String识别为有效的DateTime而显示错误.
例如.我想使用convert.todatetime将日期"06-16-2011"转换为日期时间.
but it shows error as String was not recognized as a valid DateTime.
Eg. I want to convert date "06-16-2011" as datetime using convert.todatetime.
推荐答案
try
{
CultureInfo format_dt = new CultureInfo(en-US);
dt = DateTime.ParseExact(txt_date.Text, "MM-dd-yyyy", format_dt)
}
catch (FormatException)
{
Messagebox.show(FormatException.show);
}
这是可行的
This is working
如果您想将字符串转换为日期时间,并且它将始终采用特定格式,而不是运行PC的文化,然后使用 DateTime.ParseExact [
If you want to convert a string to a date time, and it is going to always be in a specific format, rather than the culture of the PC it is running on, then use the DateTime.ParseExact[^] Method:
dt = Date.ParseExact("05-16-2011","dd-MM-yyyy", CultureInfo.InvariantCulture)
dt = convert.todatetime(txt_date.text.ToString("MM-dd-yyyy"));
这篇关于日期时间转换C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文