[英]Date Time Format String only for Milliseconds
對於一個項目,我從文件名中解析時間戳,每個時間戳都有自己的格式。 我從合作伙伴公司獲得文件,因此文件的命名是不可協商的。 現在的問題是,除了一個,每個文件名都有一個很好的時間格式,可以很容易地轉換為 c# 日期時間格式字符串,以解析為 DateTime object。不同的是,嚴格使用自初始化以來的毫秒數,因為它的時間戳相似到+4311123234_12345 M.txt
,其中下划線后的數字表示毫秒。
在此示例中,毫秒為12345
,但文件名也可以為+4311123234_123423402345802345 M.txt
,其中123423402345802345
表示毫秒。 對我來說只有毫秒部分是相關的並且是從文件名中提取的。 我現在想要一個字符串,例如“yyyy”(通常為年份),然后通過TryParseExact
方法將此數字解析為 DateTime Object。 從何時開始計算毫秒數並不重要,因為它僅用於排序,所以就我而言,它們可以是自 1900 年 1 月 00 日 00:00:00 以來經過的毫秒數。
我進行了谷歌搜索,但得出的結論是,這樣的日期時間格式字符串並不存在。 我知道有ss.fffff
但由於我不知道毫秒時間戳有多少位數,我將不得不生成一個單獨的格式字符串,其中包含相應的 'f' 數。 這也是沒有選擇的,因為格式字符串應該是用戶輸入的。
現在我將它與一個特殊的關鍵字耦合,這樣當輸入是keyword
時,時間將不會被 timeformatstring 解析,而只是被我從文件名中的部分解析為 long 得到的毫秒數。 它工作正常,但在我看來它確實不理想......我忘了說的是,包含時間戳的字符串是通過 Regex CaptureGroups 從文件名中提取的,所以在代碼示例中,時間戳字符串在cc[0]
private static void CheckForValidMatch(SortedList<DateTime, string> files, string file, Match match,string dateTimeFormat,int groupNumber)
{
Group group = match.Groups[groupNumber];
CaptureCollection cc = group.Captures;
DateTime dateTime;
if (cc.Count == 0)
Debug.WriteLine("group did not capture anything");
else
{
if (dateTimeFormat.Equals("keyword"))
{
if (long.TryParse(cc[0].ToString(),out var result))
{
dateTime = new DateTime(result);
files.Add(dateTime, file);
}
return;
}
if (!DateTime.TryParseExact(cc[0].ToString(),dateTimeFormat,DateTimeFormatInfo.CurrentInfo,DateTimeStyles.AssumeLocal, out dateTime))
Debug.WriteLine("parsing the date time failed");
else
{
files.Add(dateTime, file);
}
}
}
有沒有辦法讓它更優雅,或者有人只知道幾毫秒的格式字符串? 提前致謝!
不要期望將其直接解析為日期時間。 相反,為基准日期保留一個恆定的epoch
DateTime 值,將文件名解析為long
,然后執行以下操作:
var FileDate = epoch.AddMilliseconds(parsedLongValue);
所以我們得到這個:
private static void CheckForValidMatch(SortedList<DateTime, string> files, string file, Match match,string dateTimeFormat,int groupNumber)
{
var cc = match.Groups[groupNumber].Captures;
if (cc.Count == 0)
{
Debug.WriteLine("group did not capture anything");
return;
}
DateTime dateTime;
if (dateTimeFormat == "keyword")
{
// I don't know your epoch date, but Jan 1, 1970 is common (it's the unix epoch)
const DateTime epoch = new DateTime(1970, 1, 1);
if (long.TryParse(cc[0].ToString(),out var result))
{
dateTime = epoch.AddMilliseconds(result);
}
else
{
Debug.WriteLine($"parsing the date time for {dateTimeormat} failed");
return;
}
}
else if (!DateTime.TryParseExact(cc[0].ToString(),dateTimeFormat,DateTimeFormatInfo.CurrentInfo,DateTimeStyles.AssumeLocal, out dateTime))
{
Debug.WriteLine("parsing the date time failed");
return;
}
files.Add(dateTime, file);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.