什么是格式化的字符串日期为特定格式的最佳方式。例如,如果输入的是 30/09/2014 将被格式化为二零一四年九月三十〇日或其他类似日期格式为前?
What is the best way to format a string date to a specific format. For example if input was 30/09/2014 it would be formatted as 2014-09-30 or any other similar date format for the former?
推荐答案首先,的DateTime 不具备的任意的隐式格式。弦乐也。
First of all, DateTime doesn't have any implicit format. Strings have.
听起来像是你只需要解析您的字符串,用的 则DateTime.ToString() 方法等等;
Sounds like you just need to parse your string and format it with DateTime.ToString() method like;
string s = "30/09/2014"; DateTime dt; if(DateTime.TryParseExact(s, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt)) { dt.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture).Dump(); // Result will be 2014-09-30 }
自从我创建这个例子在 LINQPad ,的 使用.dump() 只是一个扩展方法。
Since I create this example on LINQPad, .Dump() is just an extension method.
只是要小心,当你分析一个字符串,它有 / 作为日期分隔符。 /自定义格式说明具有特殊的意义的与指定的区域性日期分隔符的当前区域性代替我的。这意味着,你的的CurrentCulture 或指定区域性的 DateSeparator 属性没有 / ,您的分析操作将失败的即使的,如果你的字符串格式是相同的格式。
Just be careful when you parse a string that have / as a date separator. "/" custom format specifier has a special meaning of replace me with the current culture of specified culture date separator. That means, your CurrentCulture or specified culture's DateSeparator property is not /, your parsing operation will fail even if your string and format are the same format.
这就是为什么我用 InvariantCulture的 在我的例子,因为它具有 / 为 DateSeparator 。
That's why I used InvariantCulture in my example since it has / as a DateSeparator.
更多推荐
格式化日期到特定格式的C#
发布评论