将字符串解析为C#DateTime对象

时间:2013-04-12 11:47:13

标签: string parsing c#-4.0 datetime

在我正在解析的XML中,我有以下内容:

<event>
    <book>Felicity Fly</book>
    <author>Christina Gabbitas</author>
    <bookImgUrl>http://www.whsmith.co.uk/Images/Products\957\255\9780957255203_t_f.jpg</bookImgUrl>
    <info>Christina Gabbitas will be signing copies of her new book, Felicity Fly. Books should be bought from WHSmith. Proof of purchase may be necessary</info>
    <date>20 Apr 2013</date>
    <startTime>10:30</startTime>
    <location>
        <name>WHSmith Chester</name>
        <address>5-7 Foregate Street</address>
        <city>Chester</city>
        <county>Cheshire</county>
        <postcode>CH1 1HH</postcode>
        <tel>01244 321106</tel>
    </location>
</event>

我想从两个节点&lt; date><startTime>创建一个DateTime对象。所以我这样做:

var EventEntity = new Event()
{
    Book = e.Book,
    BookImgUrl = e.BookImgUrl,
    Info = e.Info,
    Start = new DateTime().**?**
};

但是当我按下DateTime对象之后的点[。]时,我没有从Intellisense获取Parse方法,为什么会这样?我做错了什么?

我计划使用this post中列出的解决方案。

1 个答案:

答案 0 :(得分:1)

Parse是一个静态方法,但是你正在调用它,因为它是一个实例方法。 你应该这样称呼它:

var EventEntity = new Event()
{
    Book = e.Book,
    BookImgUrl = e.BookImgUrl,
    Info = e.Info,
    Start = DateTime.ParseExact(...) // or DateTime.TryParseExact(...)
};