简体   繁体   中英

Converting a string to DateTime object

I want to convert a string in a specific format to a DateTime .

My specific string format is " dd-mm-yyyy ".

I cannot do any string manipulations.

This is the code I have right now:

DateTime convertedDate = DateTime.Parse(stringInput);

It seems you want the static ParseExact method to which you can specify the actual date-time format.

var convertedDate = DateTime.ParseExact(input, "dd-MM-yyyy", null);

(Depending on the context, you may also want to specify CultureInfo.InvariantCulture instead of null /current culture as an argument.)

试试DateTime.ParseExact

DateTime.ParseExact("01-05-2009", "dd-MM-yyyy", null)

This sounds like a localization problem - if that is the case I recommend using one of the overloads of DateTime.parse that accepts a System.IFormatProvider. From the docs:

Type: System.IFormatProvider
An object that supplies culture-specific format information about s.

This also allows your code to be flexible - if the date format ever changes in the future to support a different culture, you can just change the format provider.

var convertedDate = DateTime.ParseExact("04-05-2010","dd-MM-yyyy",CultureInfo.InvariantCulture);
string m = "11-02-1983";

var culture = CultureInfo.CreateSpecificCulture("fr-FR");
var styles = DateTimeStyles.None;

DateTime date;
if (DateTime.TryParse(m, culture, styles, out date))
{
    //grabbed date successfully
}
else
{
    //epic fail
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM