日期时间解析 [英] DateTime parsing

查看:114
本文介绍了日期时间解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写在一个数据库接收系统日志消息,并将它们存储系统日志服务器。

I am writing a syslog server that receives syslog messages and stores them in a database.

我试图解析消息中接收到一个日期字符串< 。code>的DateTime 结构

I am trying to parse the date string received in the message into a DateTime structure.

有关在下面的例子中,我将在空白的地方为清楚使用下划线; ,实际收到的字符串有空格

For the following examples, I'll be using an underscore in place of whitespace for clarity; the actual strings received have spaces.

我收到的字符串格式为Jun__7_08:09:10 - 请注意,月份和日期之间的两个空格

The string I received is in the format "Jun__7_08:09:10" - please note the two whitespaces between the month and day.

如果这一天是10日之后,字符串变成Jun_10_08:09:10 (一个空格)

If the day is after the 10th, the strings become "Jun_10_08:09:10" (one whitespace).

如果我分析有:

DateTime.ParseExact(Log.Date, "MMM  d HH:mm:ss", CultureInfo.InvariantCulture);



它的工作从1日至9日字符串,但是从10向前抛出异常,如果我解析一个空间,它抛出1日至9日的异常(以及从第10适用于)。

it works for strings from the 1st to 9th but throws exception from the 10th forward, and if I parse with one space, it throws an exception on the 1st to 9th (and works from the 10th on).

什么是解析这个字符串的正确方法是什么?

What is the correct way to parse this string?

推荐答案

考虑使用这一行:

DateTime.ParseExact(Log.Date,
    "MMM d HH:mm:ss",
    CultureInfo.InvariantCulture,
    DateTimeStyles.AllowWhiteSpaces);

请注意,我删除月份和日之间的空间之一。这是因为 AllowWhiteSpaces 的字面意思是:

Notice that I removed one of the spaces between the month and the day. That's because AllowWhiteSpaces literally means:

指定S可以包含领先的,内在的,和尾随空格没有格式定义。

Specifies that s may contain leading, inner, and trailing white spaces not defined by format.

这篇关于日期时间解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆