UPDATE我假設有一個固定結構到FTP上市文件顯示,這樣你就可以簡單地使用String.Substring
提取時間字符串,然後用DateTime.ParseExact
解析:
var s = "-rwxr-xr-x 1 ftp ftp 267662 Jun 06 09:13 VendorInventory_20130606_021303.txt\r";
var datetime = DateTime.ParseExact(s.Substring(72,15),"yyyyMMddHHmmss",null);
Original Answer
使用正則表達式。請嘗試以下操作:
var s = "-rwxr-xr-x 1 ftp ftp 267662 Jun 06 09:13 VendorInventory_20130606_021303.txt\r";
/*
The following pattern means:
\d{8}) 8 digits (\d), captured in a group (the parentheses) for later reference
_ an underscore
(\d{6}) 6 digits in a group
\. a period. The backslash is needed because . has special meaning in regular expressions
.* any character (.), any number of times (*)
\r carriage return
$ the end of the string
*/
var pattern = @"(\d{8})_(\d{6})\..*\r$";
var match = Regex.Match(s, pattern);
string dateString = matches.Groups[1].Value;
string timeString = matches.Groups[2].Value;
和解析使用ParseExact
:
var datetime = DateTime.ParseExact(dateString + timeString,"yyyyMMddHHmmss",null);
我沒想到路過'null'成'ParseExact'的。 –
@ZevSpitz - 爲提供者傳遞'null'告訴它使用* current *文化。您可以改爲傳遞'CultureInfo.InvariantCulture'。這裏沒關係,因爲在這個特定的格式字符串中沒有文化特定的項目。 –