-2

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"]; 
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
John John
  • 1
  • 72
  • 238
  • 501
  • 3
    Does this answer your question? [Converting a String to DateTime](https://stackoverflow.com/questions/919244/converting-a-string-to-datetime) – Richard Price Jan 27 '20 at 13:47
  • 1
    https://stackoverflow.com/questions/114983/given-a-datetime-object-how-do-i-get-an-iso-8601-date-in-string-format – Ryan Thomas Jan 27 '20 at 13:48
  • 1
    If the code above actually works your value is already a `DateTime`, and you're just seeing the format the debugger is using for displaying the value. In that case you want the opposite, i.e. [`DateTime` to string](https://stackoverflow.com/q/3477735/4137916)). – Jeroen Mostert Jan 27 '20 at 13:49

3 Answers3

1

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'");
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
1

This should do the trick.

string myDate = "13/10/2019 23:00:00";

if (DateTime.TryParse(myDate, out var convertedDate))
{
     string output = convertedDate.ToString("yyyy-MM-ddTHH:mm:ssZ");
}
Ryan Thomas
  • 1,724
  • 2
  • 14
  • 27
  • 2
    And just hope that it works out in locales that use MM/dd/yyyy? – Caius Jard Jan 27 '20 at 13:53
  • The question states UK format is being followed.... – Ryan Thomas Jan 27 '20 at 13:54
  • True, but thought must always be given to future visitors to a question/simple robustitudes that can be applied to make the code more portable and less likely to develop bugs if one day they just happen to install the program in a different region – Caius Jard Jan 27 '20 at 13:56
0

If you don't want to do date/time conversions you can split and re-join the string:

var bits = i["ProjectDateSinged"].Split('/', ' ');
string newFormat = $"{bits[2]}-{bits[1]}-{bits[0]}T{bits[3]}Z";
Caius Jard
  • 72,509
  • 5
  • 49
  • 80