7

Possible Duplicate:
Convert string to DateTime in c#

How can I convert string to DateTime by a format?

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

Result is 12/11/2017 02:52:35 PM and this is incorrect because my expect is 11/17/2012 02:52:35 PM

4

5 回答 5

18

You're looking for DateTime.ParseExact().

DateTime.ParseExact(myStr, "yy/MM/dd h:mm:ss tt", CultureInfo.InvariantCulture);
于 2012-12-31T16:41:36.527 回答
3

Use DateTime.ParseExact() method.

Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.

   DateTime result = DateTime.ParseExact(yourdatestring, 
                                        "yy/MM/dd h:mm:ss tt",             
                                         CultureInfo.InvariantCulture);
于 2012-12-31T16:42:12.567 回答
1

It is better to use one of the DateTime.*Parse methods.

These take the string representing the DateTime, a format string (or array of them) and some other parameters.

The custom format string would be yy/MM/dd h:mm:ss tt.

So:

var date = DateTime.ParseExact("12/11/17 2:52:35 PM", 
                               "yy/MM/dd h:mm:ss tt"
                               CultureInfo.InvariantCulture);
于 2012-12-31T16:41:06.683 回答
1

You need to specify the 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
 */
于 2012-12-31T16:41:54.673 回答
0

尝试这个

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

“tt”是 AM/PM 指示符。

于 2012-12-31T16:48:45.327 回答