convert string in unknown format to date in c#

前端 未结 4 1200
你的背包
你的背包 2021-01-13 06:45

I have searched stackoverflow for an answer but no luck. I am developing a windows application and I have some strings in different date formats, eg.

dd/MM/y         


        
相关标签:
4条回答
  • 2021-01-13 07:09

    To run this program on different culture, i think you should creat a function to indentify the culture of this string format and then use Datetime.Parse

    0 讨论(0)
  • 2021-01-13 07:16

    Use DateTime.ParseExact with the different patterns as formats.

    If after parsing you really need to use a string representation, use the ToString method of the DateTime with the explicit format that you're interested in (so that it is culture-invariant). It's better however to keep the DateTime because this is format-agnostic.

    0 讨论(0)
  • 2021-01-13 07:24

    You could distinguish between those formats that use different separators (i.e. "/" vs "-"). But how would you know if date such as 10/11/2010 represents 10th of November or 11th of October? If one number is not bigger than 12, there is no reliable way to do this without knowing an exact format.

    As others have pointed out, if you do know the exact format, then you can use DateTime.ParseExact.

    0 讨论(0)
  • 2021-01-13 07:33

    If you are processing some import file with a lot of dates in the same unknown format, you could try different formats and hope there is exactly one that doesn't give format errors.

    Or to put it another way: split the "dates" into three numbers and check the range of values for each of those numbers. Values > 1900 will be years. If you find values from 1 to 31, those will be days. Values from 1 to 12 might be months, but could also be days. Try and identify each of the parts.

    The best way is to ask the supplier of those dates for the format.

    0 讨论(0)
提交回复
热议问题