كيف تحصل على موعد من هذه السلسلة؟
-
20-09-2019 - |
سؤال
لدي هذه السلسلة:
\tid <01CA4692.A44F1F3E@blah.blah.co.uk>; <b>Tue, 6 Oct 2009 15:38:16</b> +0100
وأريد استخراج التاريخ (نشط) إلى تنسيق أكثر قابلية للاستخدام ، على سبيل المثال 06-10-2009 15:38:16
ما هي أفضل طريقة للقيام بهذا؟
المحلول
قد يكون Regex مبالغة. فقط انقسام على "؛" ، Trim()
, ، و اتصل Date.Parse(...)
، سوف يتعامل مع إزاحة المنطقة الزمنية لك.
using System;
namespace ConsoleImpersonate
{
class Program
{
static void Main(string[] args)
{
string str = "\tid 01CA4692.A44F1F3E@blah.blah.co.uk; Tue, 6 Oct 2009 15:38:16 +0100";
var trimmed = str.Split(';')[1].Trim();
var x = DateTime.Parse(trimmed);
}
}
}
نصائح أخرى
يمكنك تجربة هذا الرمز (مع التعديلات المحتملة)
Regex regex = new Regex(
";(?<date>.+?)",
RegexOptions.IgnoreCase
| RegexOptions.CultureInvariant
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled
);
var dt=DateTime.Parse(regex.Match(inputString).Groups["date"].Value)
إليك نهج Regex لمطابقة التنسيق. يتم تنسيق نتيجة التاريخ كما حددت.
string input = @"\tid 01CA4692.A44F1F3E@blah.blah.co.uk; Tue, 6 Oct 2009 15:38:16 +0100";
// to capture offset too, add "\s+\+\d+" at the end of the pattern below
string pattern = @"[A-Z]+,\s+\d+\s+[A-Z]+\s+\d{4}\s+(?:\d+:){2}\d{2}";
Match match = Regex.Match(input, pattern, RegexOptions.IgnoreCase);
if (match.Success)
{
string result = match.Value.Dump();
DateTime parsedDateTime;
if (DateTime.TryParse(result, out parsedDateTime))
{
// successful parse, date is now in parsedDateTime
Console.WriteLine(parsedDateTime.ToString("dd-MM-yyyy hh:mm:ss"));
}
else
{
// parse failed, throw exception
}
}
else
{
// match not found, do something, throw exception
}
لا تنتمي إلى StackOverflow