[英]DateTime parsing
我正在编写一个syslog服务器,它接收syslog消息并将它们存储在数据库中。
我试图将消息中收到的日期字符串解析为DateTime
结构。
对于以下示例,为了清晰起见,我将使用下划线代替空格; 收到的实际字符串有空格。
我收到的字符串格式为"Jun__7_08:09:10"
- 请注意月和日之间的两个空格。
如果日期在10日之后,则字符串变为"Jun_10_08:09:10"
(一个空格)。
如果我解析:
DateTime.ParseExact(Log.Date, "MMM d HH:mm:ss", CultureInfo.InvariantCulture);
它适用于从第1到第9的字符串,但是从第10个向前抛出异常,如果我用一个空格解析,它会在1到9日抛出异常(并且从第10个开始工作)。
解析这个字符串的正确方法是什么?
考虑使用此行:
DateTime.ParseExact(Log.Date,
"MMM d HH:mm:ss",
CultureInfo.InvariantCulture,
DateTimeStyles.AllowWhiteSpaces);
请注意,我删除了月份和日期之间的空格。 这是因为AllowWhiteSpaces
字面意思是:
指定s可能包含未由格式定义的前导,内部和尾随空格。
使用带有格式字符串数组的DateTime.ParseExact
重载:
DateTime.ParseExact(Log.Date,
new [] {"MMM d HH:mm:ss", "MMM d HH:mm:ss"},
CultureInfo.InvariantCulture,
DateTimeStyles.None);
您可以先删除多余的空格,然后解析字符串:
DateTime.ParseExact(Log.Date.Replace(" ", " "), "MMM d HH:mm:ss", CultureInfo.InvariantCulture);
DateTime的ParseExect方法有一些重载,你可以传递多种格式,如果前一种格式不起作用 ,可以重新格式化。 这里有一个样品给你..
using System;
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"};
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"};
DateTime dateValue;
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);
}
}
}
}
// The example displays the following output:
// Converted '5/1/2009 6:32 PM' to 5/1/2009 6:32:00 PM.
// Converted '05/01/2009 6:32:05 PM' to 5/1/2009 6:32:05 PM.
// Converted '5/1/2009 6:32:00' to 5/1/2009 6:32:00 AM.
// Converted '05/01/2009 06:32' to 5/1/2009 6:32:00 AM.
// Converted '05/01/2009 06:32:00 PM' to 5/1/2009 6:32:00 PM.
// Converted '05/01/2009 06:32:00' to 5/1/2009 6:32:00 AM.
DateTime.ParseExact(date, "MMM d HH:mm:ss", CultureInfo.InvariantCulture,DateTimeStyles.AllowInnerWhite)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.