How to add a utc offset to a substring c#

99 Views Asked by At

I have a method that returns a new model as follows

return new Model
{          
    markets = response.markets
};

the markets object looks as follows:

markets: "B234851T001 - 23/08/04 11:31, B234961T002 - 23/08/04 03:43"

i need to add a UTC offset +2 to each of the dateTime. so that it would look as follows

markets: "B234851T001 - 23/08/04 13:31, B234961T002 - 23/08/04 05:43"

usually if the market object wasn't a string and just a single datetime object i would do something as follows:

markets.AddHours(2)

But i am not sure how to do this with multiple datetimes in a string to achieve the desired mentioned output? Note: i can not edit the string before its been accessed by the model

2

There are 2 best solutions below

0
Peter Dongan On BEST ANSWER
  1. Split the string
  2. parse the DateTimes
  3. adjust them
  4. rebuild the string with the corrected DateTimes

This works:

var startstring = "B234851T001 - 23/08/04 11:31, B234961T002 - 23/08/04 03:43";

var splitStrings = startstring.Split(',');
var dateStrings = splitStrings.Select(x => x.Substring(x.IndexOf("-") + 2));

var adjustedDateTimes = dateStrings.Select(x => DateTime.Parse(x).AddHours(2)).ToList();
var startOfStrings = splitStrings.Select(x => x.Substring(0, x.IndexOf("-"))).ToList();

var result = startOfStrings[0] + "- " + adjustedDateTimes[0].ToString(@"yy/MM/dd HH:mm");
for (var i = 1; i < startOfStrings.Count(); i++)
{
    result += ", " + startOfStrings[i] + "- " + adjustedDateTimes[i].ToString(@"yy/MM/dd HH:mm");
}
0
Enigmativity On

If the structure is always the same, I'd do this:

var markets = "B234851T001 - 23/08/04 11:31, B234961T002 - 23/08/04 03:43";

string AddUtc2(string input) =>
    DateTime
        .ParseExact(input, @"yy/MM/dd HH:mm", CultureInfo.CurrentCulture)
        .AddHours(2.0)
        .ToString(@"yy/MM/dd HH:mm");


var parts = markets.Split(new[] { " - ", ", " }, StringSplitOptions.None);
var output = $"{parts[0]} - {AddUtc2(parts[1])}, {parts[2]} - {AddUtc2(parts[3])}";

That produces B234851T001 - 23/08/04 13:31, B234961T002 - 23/08/04 05:43.