【发布时间】:2019-01-07 12:08:02
【问题描述】:
我正在编写一个返回日期和时间的代码(以 24 小时为单位)。我有一个在日期有效时匹配的正则表达式。我不完全知道它是否正常工作。另外,我当时需要一个正则表达式。它应该返回格式化的日期和时间。
这是一个应用程序,所以如果回复是在 c# 中,我将不胜感激。
感谢您抽出宝贵时间。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Globalization;
public class Example
{
public static void Main()
{
string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt",
"MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss",
"M/d/yyyy hh:mm tt", "M/d/yyyy hh tt",
"M/d/yyyy h:mm", "M/d/yyyy h:mm",
"MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm",
"MM/d/yyyy HH:mm:ss.ffffff",
"M-d-yyyy h:mm:ss tt", "M-d-yyyy h:mm tt",
"MM-dd-yyyy hh:mm:ss", "M-d-yyyy h:mm:ss",
"M-d-yyyy hh:mm tt", "M-d-yyyy hh tt",
"M-d-yyyy h:mm", "M-d-yyyy h:mm",
"MM-dd-yyyy hh:mm", "M-dd-yyyy hh:mm",
"MM-d-yyyy HH:mm:ss.ffffff" };
string[] dateStrings = {"5/1/2009 6:32 PM", "05/01/2009 6:32:05 PM",
"5/1/2009 6:32:00", "05/01/2009 06:32",
"05/01/2009 06:32:00 PM", "05/01/2009 06:32:00",
"08/28/2015 16:17:39.125", "08/28/2015
16:17:39.125000",
"5-1-2009 6:32 PM", "05-01-2009 6:32:05 PM",
"5-1-2009 6:32:00", "05-01-2009 06:32",
"05-01-2009 06:32:00 PM", "05-01-2009 06:32:00",
"08-28-2015 16:17:39.125", "08-28-2015
16:17:39.125000" };
DateTime dateValue;
string pattern = @"(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]|(?:Jan|Mar|May|Jul|Aug|Oct|Dec)))\1|(?:(?:1|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2]|(?:Jan|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)(?:0?2|(?:Feb))\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9]|(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep))|(?:1[0-2]|(?:Oct|Nov|Dec)))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})";
Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
MatchCollection matches = rgx.Matches(input);
if (matches.Count > 0)
{
foreach (string dateString in dateStrings)
{
try {
dateValue = DateTime.ParseExact(dateString, formats, new
CultureInfo("en-US"), DateTimeStyles.None);
Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
}
catch (FormatException) {
Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
}
}
}
}
【问题讨论】:
-
也许您可以不使用正则表达式直接解析日期时间(包括代码 sn-p):msdn.microsoft.com/de-de/library/… 或此:msdn.microsoft.com/de-de/library/9h21f14e(v=vs.110).aspx
-
您想显示日期所需的格式吗?
-
@Md.AbdulAlim 是的
-
我建议您使用具有多个 CultureInfo 的 TryParse 链或具有多种格式的 TryParseExact 链。它会更好并且执行相似(Regex 有一些开销取决于使用上下文和回溯)
标签: javascript c# regex