Parsing concatenated DateTime values

Advertisements

So I have these 2 values coming in to my program:

EDate = "20240328";
ETime = "145222"

These are essentially a timestamp of a transaction, I need to convert this to this format:

2024-03-28T19:52:22.000Z

I’ve tried a number of things and this is the only way I have found to get it right.

CultureInfo provider = CultureInfo.InvariantCulture;
DateTime dateValue;
String format = "yyyy-MM-dd\\THH:mm:ss:fff\\Z";
string EDate  = "20240328";
string ETime  = "145222";

string dtString = String.Concat(EDate, ETime);
int y = Convert.ToInt32(dtString.Substring(0,4));
int mm = Convert.ToInt32(dtString.Substring(4,2));
int dd = Convert.ToInt32(dtString.Substring(6,2));
int hh = Convert.ToInt32(dtString.Substring(8,2)) + 5; // Our servers are on Central time
int m = Convert.ToInt32(dtString.Substring(10,2));
int ss = Convert.ToInt32(dtString.Substring(12,2));

dateValue = new DateTime(y, mm, dd, hh, m, ss);
// Result: 2024-03-28T19:52:22.000Z
Console.WriteLine(dateValue.ToString(format));  

Is there an easier way?

>Solution :

This will mostly get you there:

// dateValue should be yyyyMMdd. timeValue should be HHmmss
// Will throw a FormatException if values are formatted differently.
string FormatTimestamp(string dateValue, string timeValue)
{
   string inputFormat = "yyyyMMddHHmmss";
   string outputFormat = "yyyy-MM-dd\\THH:mm:ss:fff\\Z";
   return DateTime.ParseExact(dateValue + timeValue, inputFormat, CultureInfo.InvariantCulture).ToString(outputFormat);
}

With the caveat the input hours don’t (yet!) match the desired output. And while we could .AddHours(5) easily enough, this would fail every time daylight savings changes.

So let’s make some changes to account for this:

// dateValue should be yyyyMMdd. timeValue should be HHmmss
// Will throw a FormatException if values are formatted differently.
string FormatTimestamp(string dateValue, string timeValue)
{
   string inputFormat = "yyyyMMddHHmmss";
   string outputFormat = "yyyy-MM-dd\\THH:mm:ss:fff\\Z";

   var parsedDate = DateTime.ParseExact(dateValue + timeValue, inputFormat, CultureInfo.InvariantCulture);
   var offset = TimeZoneInfo.Local.GetUtcOffset(parsedDate);

   // subtracting (add negative) to convert back to UTC
   return parsedDate.Add(-1 * offset).ToString("yyyy-MM-dd\\THH:mm:ss:fff\\Z");
}

Leave a ReplyCancel reply