Search code examples
c#date-format

Convert a formmated string (dd/mm/yy) to and ISO datetime


I have a string variable named ProjectDateSigned which have this format 13/10/2019 23:00:00, and I need to convert it to ISO standard as follow 2019-10-13T23:00:00Z, so how I can do so? i am following the UK time local.

DateTime ISOdatetimeCustom = i["ProjectDateSinged"]; 

Solution

  • ParseExact to DateTime and then format ToString back:

    string source = "13/10/2019 23:00:00";
    
    string result = DateTime
      .ParseExact(source, "d'/'M'/'yyyy' 'H':'m':'s", CultureInfo.InvariantCulture)
      .ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'");
    

    If you already have a DateTime (i.e. if i["ProjectDateSinged"] returns DateTime), just format it:

     string result = i["ProjectDateSinged"].ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'");