DateTime Conversion and Parsing DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff")

20,180

Solution 1

You can use DateTime.ParseExact:

string format = "MM/dd/yyyy hh:mm:ss.fff";
DateTime d = DateTime.ParseExact("05/15/2012 10:09:28.650",
                                format,
                                System.Globalization.CultureInfo.InvariantCulture);

Standard Date and Time Format Strings

Solution 2

use DateTime.ParseExact with specifying the format

String dateStr=DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff");
DateTime date = DateTime.ParseExact(dateStr,"MM/dd/yyyy hh:mm:ss.fff",System.Globalization.CultureInfo.InvariantCulture);

Solution 3

You should use this method to parse your string. You would have to make a class, imlementing IFormatProvider, but if you want to use a custom DateTime format, it's the best method I can think of.

Share:
20,180
Ziba Leah
Author by

Ziba Leah

Updated on July 05, 2022

Comments

  • Ziba Leah
    Ziba Leah almost 2 years

    I store some DateTime in a CSV log with:

    DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff")
    

    When I try to read it I found something like:

    "05/15/2012 10:09:28.650"
    

    The problem is when I try to cast it as a DateTime again...

    DateTime.Parse("05/15/2012 10:09:28.650");
    

    Throws an Exception "Invalid DateTime" or something like that...

    How can I properly re-read the DateTime?