如何通过格式将字符串转换为Datetime?

时间:2012-12-31 16:39:52

标签: c# string datetime format

  

可能重复:
  Convert string to DateTime in c#

如何通过格式将字符串转换为DateTime?

Convert.ToDateTime("12/11/17 2:52:35 PM")

结果为12/11/2017 02:52:35 PM,这是不正确的,因为 我的期望是11/17/2012 02:52:35 PM

5 个答案:

答案 0 :(得分:14)

您正在寻找DateTime.ParseExact()

DateTime.ParseExact(myStr, "yy/MM/dd h:mm:ss tt", CultureInfo.InvariantCulture);

答案 1 :(得分:3)

使用DateTime.ParseExact()方法。

  

将指定的日期和时间字符串表示形式转换为它   DateTime等效使用指定的格式和特定​​于文化   格式信息。字符串表示的格式必须匹配   准确的指定格式。

   DateTime result = DateTime.ParseExact(yourdatestring, 
                                        "yy/MM/dd h:mm:ss tt",             
                                         CultureInfo.InvariantCulture);

答案 2 :(得分:1)

最好使用DateTime.*Parse方法之一。

这些字符串表示DateTime,格式字符串(或它们的数组)和其他一些参数。

custom format stringyy/MM/dd h:mm:ss tt

所以:

var date = DateTime.ParseExact("12/11/17 2:52:35 PM", 
                               "yy/MM/dd h:mm:ss tt"
                               CultureInfo.InvariantCulture);

答案 3 :(得分:1)

您需要指定culture of the string

// 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
 */

答案 4 :(得分:0)

试试这个

dateValue = DateTime.ParseExact(dateString,
                                "yy/MM/dd hh:mm:ss tt",
                                new CultureInfo("en-US"),
                                DateTimeStyles.None);

“tt”是AM / PM指示符。