C#将字符串日期格式转换为另一个字符串的最佳方法? [英] C# Best way to convert string date format to another string?
问题描述
我将以下日期存储为字符串
I have the following date stored as a string
04.09.2009 (dd.mm.yyyy)
现在我希望将其更改为以下格式:
Now I would like it changed to this format:
2009/08/31 (yyyy/mm/dd)
请记住,输出应为字符串值,输入日期为字符串。
Remember output should be a string value and the input date is a string.
用最少的精力转换它的最佳方法是什么?
What is the best way to convert it with minimal effort?
推荐答案
为什么要将日期存储为字符串?通常这是个坏主意...
Why are you storing the date as a string? That's generally a bad idea...
要将您解析的字符串转换为DateTime值,并将其格式转换为字符串:
To convert the string you parse it into a DateTime value, the format that into a string:
string newFormat = DateTime.ParseExact(theDate, "dd'.'MM'.'yyyy", CultureInfo.InvariantCulture).ToString("yyyy'/'MM'/'dd")
(请注意,您需要在斜杠两边加上撇号,以获取原义字符,否则,它将使用区域性的日期分隔符,该字符可能是不同的字符。)
(Note that you need apostrophes around the slashes to get the literal character, otherwise it will use the date separator character of the culture, which may be a different character.)
这篇关于C#将字符串日期格式转换为另一个字符串的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!