我有一个来自外部的价值 我正在获取字符串值(07/03/2011 12:00:00 AM),我想转换为DateTime并更新数据库. 目前,我正在尝试以下方法,但还是不行... 选项1:
Hi i have a value coming from external Am getting string value (07/03/2011 12:00:00 AM ) and i want to convert to DateTime and update the Database. At present am trying below methods but still no go... Option 1:
DateTime myDateTime = System.Convert.ToDateTime(item.StartDate);选项2:
Option 2:
string strDateTime = sampledate; //(when i use this "it shows Cannot implicitly convert type system.DateTime ? to String) DateTime myDateTime = DateTime.Parse(strDateTime );请有人指导我转换的正确方法是什么 更新1: 下面的代码正在工作
Please some one guide me what is the right way to convert Update 1: The below code is working
DateTime strDateTime = System.Convert.ToDateTime(item.StartDate); string conv=System.Convert.ToString (strDateTime); DateTime dateToSave; bool canParse = DateTime.TryParse(conv, out dateToSave); if (canParse) { Console.WriteLine("Testok"); } else { Console.WriteLine("Fail"); }推荐答案
使用重载的方法之一System.DateTime.Parse或System.DateTime.ParseExact.
使用DateTime.TryParse方法. 方法是这样的: Use DateTime.TryParse method. This is how it is done: DateTime dateTime; DateTime.TryParse(strDateTime, out dateTime);
最酷的部分是TryParse如果解析成功将返回True,如果解析失败则返回False.您可以在if条件下使用该语句. 更新1:
The coolest part is TryParse will return True if the parsing is successful and return False if the parsing fail. You can either use the statement in a if condition. Update 1:
shan1395写道: shan1395 wrote:DateTime strDateTime = System.Convert.ToDateTime(item.StartDate);
DateTime strDateTime = System.Convert.ToDateTime(item.StartDate);
此代码是将字符串转换为DateTime的方法之一.如果您使用Convert.ToDateTime ,则不需要使用TryParse. 如果字符串为空,则Convert.ToDateTime将失败并引发异常.但是TryParse不会引发异常. 解决方案1:
This code is one of the ways to convert string to DateTime. It is not required to use TryParse if you use Convert.ToDateTime Convert.ToDateTime will fail and throw exception if the string is empty. But TryParse will not throw exception. Solution 1:
DateTime dateTime = System.Convert.ToDateTime(item.StartDate);或 解决方案2:
or Solution 2:
DateTime dateTime; DateTime.TryParse(item.StartDate, out dateTime);如果有帮助,请将其标记为答案
Mark it as answer if it is helpful
更多推荐
将DateTime字符串转换为Datetime
发布评论