正则表达式将月份名称转换为月份号码 [英] Regex to convert month name to month number
问题描述
我的问题很简单,虽然我发现了许多与我的问题相关的片段,但我还没找到我的解决方案。
My problem is quite simple, although I have found many snippets related to my question, I have not found my solution.
我需要的是一个正则表达式和替代品字符串(未嵌入任何编程语言)转换为日期,如2017年12月31日至2017年12月31日
What I need is a regex expression and substitute string (not embedded in any progamming language) to convert as date such as 31-Dec-2017 to 31.12.2017
谢谢
推荐答案
你有什么奇怪的要求说你必须使用正则表达式吗?因为虽然它是一个强大的工具,但我认为有些人会尝试使用它,即使没有必要也可以使用它!
Do you have some kind of strange requirement that says you MUST use a regex? Because although it is a powerful tool, I do think some people try and use it at any opportunity even if unnecessary!
我个人认为,使用正则表达式可以解决的问题是不正确的用法,如果你最终需要处理不同的语言等,可能会导致问题和错误。
Personally, I would say that using a regex for what you are asking is not the correct usage and will potentially lead to problems and bugs if, for example, you end up needing to deal with different languages etc.
我的建议是:
1)除非你绝对没有选择,否则不要使用字符串来保存日期和时间信息。使用DateTime变量来保存日期/时间信息,只有在需要将其输出给用户时才转换为字符串。为此,将DateTime.ToString()与
一起使用为适当的格式。例如
1) Don't use strings to hold date and time information at all unless you have absolutely no choice. Use DateTime variables to hold date/time info and only convert to a string when you need to output it to the user. For this, use DateTime.ToString() with an appropriate format. e.g
string result = dt.ToString("dd.MM.yyyy")
2)如果你已经有一个包含文字"2017年12月31日"的字符串。并且你无法避免它(它来自用户输入或其他东西),然后使用DateTime.Parse()或DateTime.ParseExact()来获取DateTime,然后转换回你想要的格式
当你需要按照步骤1中的说明输出
2) If you already have a strings containing the text "31-Dec-2017" and you can't avoid it (its from user input or something), then use DateTime.Parse() or DateTime.ParseExact() to get a DateTime first, and then convert back to the format you want when you need to output as noted in step 1
DateTime dt = DateTime.ParseExact("02-Dec-2017", "dd-MMM-yyyy", null);
Console.WriteLine(dt.ToString("dd.MM.yyyy"));
这篇关于正则表达式将月份名称转换为月份号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!