C# C中从字符串开始的时间戳解析#
我正在用.NET重新编写一个现有的Java软件解决方案。Java解决方案在某一时刻读取字符串开头的时间戳,如下所示:C# C中从字符串开始的时间戳解析#,c#,.net,datetime,parsing,timestamp,C#,.net,Datetime,Parsing,Timestamp,我正在用.NET重新编写一个现有的Java软件解决方案。Java解决方案在某一时刻读取字符串开头的时间戳,如下所示: SimpleDateFormat dateFormat = new SimpleDateFormat(timeFormat); dateFormat.setLenient(false); try { timeStamp = dateFormat.parse(line); } catch (ParseException e) { //... } private
SimpleDateFormat dateFormat = new SimpleDateFormat(timeFormat);
dateFormat.setLenient(false);
try
{
timeStamp = dateFormat.parse(line);
}
catch (ParseException e)
{
//...
}
private static DateTime GetDate(string line)
{
int index = 0;
DateTime theDate;
string s = line;
while(!DateTime.TryParse(s, out theDate))
{
index = line.IndexOf(" ", index);
s = line.Substring(0, index);
}
return theDate;
}
现在我正试图在C#中做同样的事情:
这两种语言都可以工作,直到我在line变量的时间戳之后添加一些随机文本为止。Java将忽略它,但C#将不允许在该行中的时间戳文本之后执行任何其他操作
因此,尽管Java乐于将“01/01/01 01:01:01001 Hello World!”解析为时间戳,但C#不是,因为格式字符串中没有指定“Hello World!”
但是,由于我无法对字符串中的时间戳之后可能出现的内容做出任何声明,因此我无法将其包含在格式字符串中
有什么想法吗
提前谢谢。如果您知道日期的格式和存储环境,那么这是一个优势 例如,如果您知道您正在存储昨天的日志或类似内容:
DateTime yesterday = DateTime.Today.AddDays(-1);
timestamp = DateTime.Parse(
line.SubString(0, line.IndexOf(yesterday.Year.ToString()) + 4));
编辑:日期后的文本是否有任何分隔符(甚至空格)
如果有,您可以这样做:
SimpleDateFormat dateFormat = new SimpleDateFormat(timeFormat);
dateFormat.setLenient(false);
try
{
timeStamp = dateFormat.parse(line);
}
catch (ParseException e)
{
//...
}
private static DateTime GetDate(string line)
{
int index = 0;
DateTime theDate;
string s = line;
while(!DateTime.TryParse(s, out theDate))
{
index = line.IndexOf(" ", index);
s = line.Substring(0, index);
}
return theDate;
}
注意:如果日期后有文本,则无法获取时间(因为在搜索时它将能够在没有时间的情况下成功解析出日期)。您可以通过获取从行末尾开始并向后移动的空格索引来修复此问题。我将把这个留给你。如果你知道你的日期将采用什么格式,以及它的存储环境,那么这是一个优势 例如,如果您知道您正在存储昨天的日志或类似内容:
DateTime yesterday = DateTime.Today.AddDays(-1);
timestamp = DateTime.Parse(
line.SubString(0, line.IndexOf(yesterday.Year.ToString()) + 4));
编辑:日期后的文本是否有任何分隔符(甚至空格)
如果有,您可以这样做:
SimpleDateFormat dateFormat = new SimpleDateFormat(timeFormat);
dateFormat.setLenient(false);
try
{
timeStamp = dateFormat.parse(line);
}
catch (ParseException e)
{
//...
}
private static DateTime GetDate(string line)
{
int index = 0;
DateTime theDate;
string s = line;
while(!DateTime.TryParse(s, out theDate))
{
index = line.IndexOf(" ", index);
s = line.Substring(0, index);
}
return theDate;
}
注意:如果日期后有文本,则无法获取时间(因为在搜索时它将能够在没有时间的情况下成功解析出日期)。您可以通过获取从行末尾开始并向后移动的空格索引来修复此问题。我将把它留给您。看起来.Net将解析整个字符串,而您无法控制整个字符串。我会说使用TryParse(),如果失败,请从字符串中去掉最右边的“单词”,然后重试。我对Java不熟悉,但它可能会在幕后完成这项工作。看起来.Net将解析整个字符串,而您无法控制整个字符串。我会说使用TryParse(),如果失败,请从字符串中去掉最右边的“单词”,然后重试。我不熟悉Java,但它可能会在幕后完成这项工作。试试这个:
Dictionary<string, string> tests = new Dictionary<string,string>()
{
{ "yy/MM/dd HH:mm:ss,fff", "01/01/01 01:01:01,001 Hello World!"},
{ "yyyyMMddHHmmssfff", "2009111615413829403 Hello World!"},
{ "d.M.yyyy H:m:s,fff", "8.10.2009 8:17:26,338 Hello World!" }
};
foreach(KeyValuePair<string, string> test in tests)
{
string pattern = test.Key;
string format = test.Value;
DateTimeFormatInfo dateTimeFormatInfo = new DateTimeFormatInfo();
dateTimeFormatInfo.FullDateTimePattern = pattern;
Console.WriteLine("{0} - {1}", pattern, format);
DateTime timeStamp = DateTime.MinValue;
if (pattern.Contains(' ')) // approach 1: split and conquer
{
format = String.Join(" ", format
.Split(" ".ToCharArray())
.Take(pattern.Count(c => c == ' ') + 1));
}
else
{
format = format.Substring(0, pattern.Length);
}
if (!DateTime.TryParseExact(
format, pattern, dateTimeFormatInfo,
DateTimeStyles.AllowWhiteSpaces, out timeStamp))
{
Console.WriteLine("\tSomething sad happened");
}
else
{
Console.WriteLine("\t{0}", timeStamp.ToString(pattern));
}
}
Console.Read();
字典测试=新字典()
{
{“yy/MM/dd HH:MM:ss,fff”,“01/01/01 01:01:01001你好,世界!”),
{“yyyymmddhhmmssff”,“2009111615413829403你好,世界!”,
{“d.M.yyyy H:M:s,fff”,“8.10.2009 8:17:26338你好,世界!”
};
foreach(测试中的KeyValuePair测试)
{
字符串模式=test.Key;
字符串格式=test.Value;
DateTimeFormatInfo DateTimeFormatInfo=新的DateTimeFormatInfo();
dateTimeFormatInfo.FullDateTimePattern=模式;
WriteLine(“{0}-{1}”,模式,格式);
DateTime timeStamp=DateTime.MinValue;
if(pattern.Contains(“”))//方法1:拆分并征服
{
格式=字符串。连接(“),格式
.Split(“.ToCharArray())
.Take(pattern.Count(c=>c='')+1);
}
其他的
{
format=format.Substring(0,pattern.Length);
}
如果(!DateTime.TryParseExact)(
格式、模式、日期时间格式信息、,
DateTimeStyles.AllowHiteSpaces,输出时间戳)
{
Console.WriteLine(“\t发生了什么伤心事”);
}
其他的
{
Console.WriteLine(“\t{0}”,timeStamp.ToString(模式));
}
}
Console.Read();
注意我没有使用DateTime.Parse
,因为如果字符串不是有效的DateTime
格式字符串,它会引发异常
更新1:更好的输入处理,因为不需要空白,而是使用模式长度
更新2:之前的两种方法合并到此代码中;我知道在测试2中使用一个d
,但我认为我们对此无能为力。试试这个:
Dictionary<string, string> tests = new Dictionary<string,string>()
{
{ "yy/MM/dd HH:mm:ss,fff", "01/01/01 01:01:01,001 Hello World!"},
{ "yyyyMMddHHmmssfff", "2009111615413829403 Hello World!"},
{ "d.M.yyyy H:m:s,fff", "8.10.2009 8:17:26,338 Hello World!" }
};
foreach(KeyValuePair<string, string> test in tests)
{
string pattern = test.Key;
string format = test.Value;
DateTimeFormatInfo dateTimeFormatInfo = new DateTimeFormatInfo();
dateTimeFormatInfo.FullDateTimePattern = pattern;
Console.WriteLine("{0} - {1}", pattern, format);
DateTime timeStamp = DateTime.MinValue;
if (pattern.Contains(' ')) // approach 1: split and conquer
{
format = String.Join(" ", format
.Split(" ".ToCharArray())
.Take(pattern.Count(c => c == ' ') + 1));
}
else
{
format = format.Substring(0, pattern.Length);
}
if (!DateTime.TryParseExact(
format, pattern, dateTimeFormatInfo,
DateTimeStyles.AllowWhiteSpaces, out timeStamp))
{
Console.WriteLine("\tSomething sad happened");
}
else
{
Console.WriteLine("\t{0}", timeStamp.ToString(pattern));
}
}
Console.Read();
字典测试=新字典()
{
{“yy/MM/dd HH:MM:ss,fff”,“01/01/01 01:01:01001你好,世界!”),
{“yyyymmddhhmmssff”,“2009111615413829403你好,世界!”,
{“d.M.yyyy H:M:s,fff”,“8.10.2009 8:17:26338你好,世界!”
};
foreach(测试中的KeyValuePair测试)
{
字符串模式=test.Key;
字符串格式=test.Value;
DateTimeFormatInfo DateTimeFormatInfo=新的DateTimeFormatInfo();
dateTimeFormatInfo.FullDateTimePattern=模式;
WriteLine(“{0}-{1}”,模式,格式);
DateTime timeStamp=DateTime.MinValue;
if(pattern.Contains(“”))//方法1:拆分并征服
{
格式=字符串。连接(“),格式
.Split(“.ToCharArray())
.Take(pattern.Count(c=>c='')+1);
}
其他的
{
format=format.Substring(0,pattern.Length);
}
如果(!DateTime.TryParseExact)(
格式、模式、日期时间格式信息、,
DateTimeStyles.AllowHiteSpaces,输出时间戳)
{
Console.WriteLine(“\t发生了什么伤心事”);
}
其他的
{
Console.WriteLine(“\t{0}”,timeStamp.ToString(模式));
}
}
Console.Read();
注意我没有使用DateTime.Parse
,因为如果字符串不是有效的DateTime
格式字符串,它会引发异常
更新1:更好的输入处理,因为不需要空白,而是使用模式长度
更新2:之前的两种方法合并到此代码中;我知道在测试2中使用单个
d
,但我认为我们对此无能为力。您能保证文件中的日期格式始终相同吗?就拿fi来说吧