In the programming world, processing date and time are a common task. Sometimes, we will encounter these values storage as string, for example:
2009-05-08 14: 40: 52,531
In order to convert these strings into available DateTime objects, we have several options. One method is to specify the custom format string, as shown below:
By specifying the custom format string, we can ensure that the elements of the string (year-month-day, hour-second-seconds, and milliseconds) are aligned with the expected DateTime format. This method provides a reliable and efficient way to convert the string to Datetime object.
using System; using System.Globalization; namespace DateTimeParsingExample { class Program { static void Main(string[] args) { // 指定自定义格式字符串以适应字符串的组成 string formatString = "yyyy-MM-dd HH:mm:ss,fff"; // 使用自定义格式解析字符串 DateTime myDate = DateTime.ParseExact("2009-05-08 14:40:52,531", formatString, CultureInfo.InvariantCulture); // 输出解析的日期 Console.WriteLine(myDate.ToString()); // 显示 2009-05-08 14:40:52,531 } } }
The above is the detailed content of How Can I Parse a String into a DateTime Object in C#?. For more information, please follow other related articles on the PHP Chinese website!