💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# 如何:将字符串转换为 DateTime(C# 编程指南) 通常程序需要支持用户以字符串值的形式输入日期。若要将基于字符串的日期转换为 [System.DateTime](https://msdn.microsoft.com/zh-cn/library/system.datetime.aspx) 对象,可以使用 [Convert.ToDateTime(String)](https://msdn.microsoft.com/zh-cn/library/xhz1w05e.aspx) 方法或 [DateTime.Parse(String)](https://msdn.microsoft.com/zh-cn/library/1k1skd40.aspx) 静态方法,如下面的示例所示。 有关日期字符串的更多示例,请参见 [Convert.ToDateTime(String)](https://msdn.microsoft.com/zh-cn/library/xhz1w05e.aspx)。 ``` // Date strings are interpreted according to the current culture. // If the culture is en-US, this is interpreted as "January 8, 2008", // but if the user's computer is fr-FR, this is interpreted as "August 1, 2008" string date = "01/08/2008"; DateTime dt = Convert.ToDateTime(date); Console.WriteLine("Year: {0}, Month: {1}, Day: {2}", dt.Year, dt.Month, dt.Day); // Specify exactly how to interpret the string. IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true); // Alternate choice: If the string has been input by an end user, you might // want to format it according to the current culture: // IFormatProvider culture = System.Threading.Thread.CurrentThread.CurrentCulture; DateTime dt2 = DateTime.Parse(date, culture, System.Globalization.DateTimeStyles.AssumeLocal); Console.WriteLine("Year: {0}, Month: {1}, Day {2}", dt2.Year, dt2.Month, dt2.Day); /* Output (assuming first culture is en-US and second is fr-FR): Year: 2008, Month: 1, Day: 8 Year: 2008, Month: 8, Day 1 */ ``` ## 请参阅 [字符串(C# 编程指南)](https://msdn.microsoft.com/zh-cn/library/ms228362.aspx)