Search code examples
c#datetimeoffset

How to add a utc offset to a substring c#


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


Solution

    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");
    }