Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How to get DateTime from ISO 8601 string?

Discussion in 'Scripting' started by QuantumCalzone, Apr 11, 2018.

  1. QuantumCalzone

    QuantumCalzone

    Joined:
    Jan 9, 2010
    Posts:
    262
    In my server, my dates are saved as a string in the ISO 8601 format. Example "2018-04-11T05:59:19.000Z"

    How would I convert this string to a DateTime in c#?
     
  2. andymads

    andymads

    Joined:
    Jun 16, 2011
    Posts:
    1,614
  3. QuantumCalzone

    QuantumCalzone

    Joined:
    Jan 9, 2010
    Posts:
    262
    I actually did and tried the top answer on that very post (including the suggested amendment on the top answer) and found that I get errors.

    Code (CSharp):
    1.  
    2.     public void TestConversion1 () {
    3.         string exampleDateISO = "2018-04-11T05:59:19.000Z";
    4.         DateTime dateFromISO = DateTime.Parse(exampleDateISO, null, System.Globalization.DateTimeStyles.RoundtripKind);
    5.         print(dateFromISO.ToLongTimeString());
    6.     }
    7.  
    8.     public void TestConversion2 () {
    9.         string exampleDateISO = "2018-04-11T05:59:19.000Z";
    10.         DateTime dateFromISO = DateTime.Parse(exampleDateISO, null, System.Globalization.DateTimeStyles.RoundtripKind);
    11.         print(dateFromISO.ToLongTimeString());
    12.     }
    13.  
    I notice that my string has some extra digits but not exactly sure what I'm supposed to adapt to get the conversion to work? Thanks for your time!
     
  4. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    Use a regex to format the string in a way that DateTime.Parse will accept. Or use a regex to just parse the whole thing yourself. If you've never used regular expressions, the topic is too big to teach in a forum response, but there are plenty of websites that teach them.