Chris Barry
Chris Barry

Reputation: 4594

How to apply difference in DateTime to a list of DateTime objects in c#

I have some code which detects when properties are changed on objects, which are persisted to the db. The detection happens before they are saved back to the db.

I want to know the best way to apply the change in time to a whole set of related log items.

Say I have an item with a datetime of

01/01/2000 00:00:00

and I change it to

02/01/2000 06:00:00

I know I need to move each log item forward by 1 day and 6 hours. Should I be manually writing code to handle all this, or does .net have some smooth way of handling this for me. DateTimeOffset sounded like the right idea, but I don't think it is used for this.

If I was to build this myself, I would probably calculate a timespan, and if the span should be added or subtracted from the DateTime. But is there something better?

Upvotes: 0

Views: 193

Answers (4)

Sascha
Sascha

Reputation: 10347

You can do this using LINQ using a one liner:

datetimes = datetimes.Select ( itm => itm.AddDays ( 1 ).AddHours ( 6 ) ).ToArray ();

If this is more readable than a foreach loop is left open for you to decide for yourself.

Upvotes: 0

default locale
default locale

Reputation: 13456

What's the problem with TimeSpan class?

TimeSpan timeSpan = finishDate - startDate;
for (int index = 0; index < dateList.Count; index++)
    {
        dateList[index] = dateList[index] + timeSpan;
    }

Here timeSpan initialized as a difference of two dates. But you can initialize it in other ways, check TimeSpan constructors.

Timespan class does work with negative time intervals. Try to check it.

DateTime start = new DateTime(2010, 10, 26);
DateTime finish = new DateTime(2010, 10, 20);
TimeSpan diff = finish - start;
DateTime value = new DateTime(2010, 11, 1);
value += diff;
Console.WriteLine(diff);
Console.WriteLine(value.ToString("dd.M.yyyy"));

Output:

-6.00:00:00
26.10.2010

Upvotes: 1

Mark Avenius
Mark Avenius

Reputation: 13947

TimeSpan will work for you, and yes, it does keep track of positive and negative. The Duration() method on the TimeSpan will return a new TimeSpan that has the absolute value of the original value (i.e. the positive change).

That being said, with the following you won't have to worry about positive or negative changes:

        DateTime[] dateTimeArray = {DateTime.Now};
        foreach (DateTime dateTime in dateTimeArray)
        {
            dateTime.Add(timeSpan);
        }

Upvotes: 3

Albin Sunnanbo
Albin Sunnanbo

Reputation: 47058

Just use the Add* methods on the DateTime object.

DateTime d1 = DateTime.Now;
d1 = d1.AddDays(1).AddHours(6);

Upvotes: 1

Related Questions