Paul
Paul

Reputation: 3293

Date Time Offset not working

I am not very familiar with dealing with date time spans etc in C#

Please see my test below

I am giving it 2 dates

I then want to change the dates to be offset from the replay date

This works perfect for the first date

But my second date is not working I need it to be 13:05 but its 13:00

        var dates = new List<DateTime>()
        {
            Convert.ToDateTime("29/06/2018 10:00"),
            Convert.ToDateTime("29/06/2018 10:05")
        };

        var replayDate = Convert.ToDateTime("29/06/2018 13:00");

        for (var index = 0; index < dates.Count; index++)
        {
            var date = dates[index];

            var time = replayDate.TimeOfDay - date.TimeOfDay;

            var newTime = date.Add(time);
            dates[index] = newTime;
        }

        Assert.AreEqual(Convert.ToDateTime("29/06/2018 13:00"), dates[0]);
        Assert.AreEqual(Convert.ToDateTime("29/06/2018 13:05"), dates[1]);

Whats the best approach to do this?

Paul

Upvotes: 0

Views: 91

Answers (1)

Rafalon
Rafalon

Reputation: 4515

Maybe try the following:

var dates = new List<DateTime>
{
    Convert.ToDateTime("29/06/2018 10:00"),
    Convert.ToDateTime("29/06/2018 10:05")
};

var replayDate = Convert.ToDateTime("29/06/2018 13:00");
// process the offset once (before the loop) -- here it will be 3 hours
var offset = replayDate.TimeOfDay - dates[0].TimeOfDay;

for (var index = 0; index < dates.Count; index++)
{
    // shift all your dates by that offset
    dates[index] = dates[index].Add(offset);
}

Assert.AreEqual(Convert.ToDateTime("29/06/2018 13:00"), dates[0]);
Assert.AreEqual(Convert.ToDateTime("29/06/2018 13:05"), dates[1]);

As per my comment:

time should be replayDate.TimeOfDay - dates[0].TimeOfDay - you want the offset to be the difference between your replayDate and the first date, this should therefore also be outside (before) the loop.

Here is a code snippet to demonstrate.
Note that I formatted the date strings as MM/dd/yyyy HH:mm because of the server's culture.

Upvotes: 2

Related Questions