开发者

Get DateTime Obj from "mm/yyyy" format Date string

开发者 https://www.devze.com 2022-12-12 06:24 出处:网络
I have a date string in format \"08/1999\" I want to get the first date of the corresponding month. eg : in this case 08/01/1999.

I have a date string in format "08/1999" I want to get the first date of the corresponding month. eg : in this case 08/01/1999. It is simple for en-Us culture. I break the string, append "01" in the string to get 08/01/1999 and then DateTime.Parse(datestring) but this is valid for en-US culture only.

How can I do this for different culture ?

My datestring will always be 开发者_运维百科in mm/yyyy format. and I am trying to obtain a DataTime obj from this dateString.


Use ParseExact method. Note upper-cased M's are for months and lower-cased m's for minutes.

string dateToConvert = "08/1999";
string format = "MM/yyyy";
CultureInfo provider = CultureInfo.InvariantCulture;

DateTime result = DateTime.ParseExact(dateToConvert, format, provider); 

Output:

{1999-08-01 00:00:00}

You can also use Convert.ToDateTime and Parse methods. It will produce the same result, but in implicite way:

DateTime result = Convert.ToDateTime(dateToConvert, provider); // Output: {1999-08-01 00:00:00}
DateTime result = DateTime.Parse(dateToConvert, provider); // Output: {1999-08-01 00:00:00}

Read more at:

  • Parsing Date and Time Strings
  • Standard Date and Time Format Strings
  • Custom Date and Time Format Strings


I'm not sure if I understand your question correctly, but you can try passing CultureInfo.InvariantCulture if you want to force the US date format regardless of the regional settings of the client computer:

DateTime.Parse("08/1999", System.Globalization.CultureInfo.InvariantCulture)


I break the string, append "01" in the string to get 08/01/1999 and then DateTime.Parse(datestring)

That's a very long-winded way to do it. Simply this will work:

DateTime.Parse("08/1999")

How can I do this for different culture ?

If your string is always in this format, do this:

DateTime.Parse("08/1999", CultureInfo.InvariantCulture)

0

精彩评论

暂无评论...
验证码 换一张
取 消