我正在使用date function.data有不同的格式,例如
1."2016-01-31"
2."2016-01-31"
3."2016/1/31"
4."2016/01/31"
5."2016年01月01日"
6."2016-01-02 12:00上午"
现在我想将上述所有格式日期转换为日期时间格式 YYYY-mm-dd。
我尝试了很多方法,但某些格式显示错误消息,例如
"字符串格式不正确"
"无法将字符串值转换为日期时间"
我试过了
Datetime date=DateTime.ParseExact(txtdate.Text,'YYYY-mm-dd',CultureInfo.InvariantCulture);
如何从任何格式文本框值将值转换/转换为日期时间格式(YYYY-mm-dd)。
大多数情况下,我在上传到服务器(GoDaddy 和 Microsoft azure)后出现错误。
我可以这样使用吗
字符串日期时间=txtdate。发短信;
string[] dateTimes = new string[] { "YYYY-mm-dd", "dd-mm-YYYY","mm/dd/YYYY","yyyy/MM/dd"};
你的代码不太正确。日期格式字符串应用"(双引号)括起来,大小写应类似于"yyyy-MM-dd"。CultureInfo.InvariantCulture
拼写也不正确。
话虽如此,您不需要使用 ParseExact
函数将字符串转换为DateTime
格式。您可以简单地使用Convert.ToDateTime
以下是我用来测试 Convert.DateTime
函数的一些示例代码:
string[] dateTimes = new string[] { "2010-02-01", "02-03-2011", "03/04/2012", "2013/05/04", "june 05 2014", "2015-07-06 11:00 AM" };
StringBuilder sb = new StringBuilder();
foreach (string date in dateTimes)
{
DateTime dt = Convert.ToDateTime(date);
sb.AppendLine(dt.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture));
}
string convertedDateTimes = sb.ToString();
使用上面的相关部分,您可以将代码更改为以下内容:
try
{
Datetime date = Convert.ToDateTime(txtdate.Text.Trim());
string dateString = date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
}
catch (FormatException ex)
{
//Handle the exception. e.g. show a message or print something to the form.
}