Search code examples
c++c++-climanaged-c++

Parsing string to datetime


I'm writing a application on managed c++ so my problem is I can't seem to find fast and easy way to parse this string to DateTime:

2011-11-21 18:24:58

Solution

  • Have you tried

    using namespace System;
    DateTime^ dt = gcnew DateTime;
    dt = DateTime::Parse("2011-11-21 18:24:58");
    

    If Parse is unable to parse your string into a date time, it will throw an FormatException, which you can catch and examine the error to see why it failed.

    try
    {
        using namespace System;
        DateTime^ dt = gcnew DateTime;
        dt = DateTime::Parse("2011-11-21 18:24:58");
    }
    catch (FormatException^ e)
    {
        System::Console::WriteLine(e->Message);
    }