tags:

views:

61

answers:

4

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?

+1  A: 

Just use the Add* methods on the DateTime object.

DateTime d1 = DateTime.Now;
d1 = d1.AddDays(1).AddHours(6);
Albin Sunnanbo
Thats fine, but what if the time moved backwards? The numbers of the timespan would be positive, but should be applied negatively. I am wondering if I should have my own variable to say add/substract. And if it is subtract, then the values are flipped. d1.AddDays(-1).AddHours(-6);
optician
Yes, just "add" negative values.
Albin Sunnanbo
+1  A: 

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
MAKKAM
Does the timespan record if the span is forwards in time or backwards?
optician
Yes, TimeSpan class implements negative time intervals. You can easily check it.
MAKKAM
+2  A: 

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);
        }
Mark Avenius
A: 

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.

Sascha