格式化日期到特定格式的C#

编程入门 行业动态 更新时间:2024-10-17 11:23:39
本文介绍了格式化日期到特定格式的C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

什么是格式化的字符串日期为特定格式的最佳方式。例如,如果输入的是 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#

本文发布于:2023-11-07 19:37:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1567236.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:日期   格式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!