using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Convert2DateTime { class Program { static void Main(string[] args) { DateTime dt; DateTime dt2; //1.将string 转化为datetime类型; Convert.ToDateTime的用法; try { dt = Convert.ToDateTime("2015/07/03"); Console.WriteLine("dt1 = {0}",dt); } catch (FormatException ex) { Console.WriteLine("The data's format is wrong."); } catch (Exception ex) { Console.WriteLine("check the try ."); } //2. 将string 转化为datetime类型; DateTime.TryParse的用法,返回值为bool,第一个参数为string, 第二个参数为out DateTime; if (!DateTime.TryParse("2015/07/04", out dt2)) { Console.WriteLine("The data's format is wrong."); } else { Console.WriteLine("dt2 = {0}", dt2); } Console.ReadKey(); } } }
转载于:https://blog.51cto.com/57388/1670537