Converting a String to DateTime

后端 未结 17 2599
南方客
南方客 2020-11-21 06:12

How do you convert a string such as 2009-05-08 14:40:52,531 into a DateTime?

17条回答
  •  长发绾君心
    2020-11-21 06:55

    Do you want it fast?

    Let's say you have a date with format yyMMdd.

    The fastest way to convert it that I found is:

    var d = new DateTime(
    (s[0] - '0') * 10 + s[1] - '0' + 2000, 
    (s[2] - '0') * 10 + s[3] - '0', 
    (s[4] - '0') * 10 + s[5] - '0')
    

    Just, choose the indexes according to your date format of choice. If you need speed probably you don't mind the 'non-generic' way of the function.

    This method takes about 10% of the time required by:

    var d = DateTime.ParseExact(s, "yyMMdd", System.Globalization.CultureInfo.InvariantCulture);
    

提交回复
热议问题