I have an array of objects for events, things that happened in the past. They can be relatively vast, and for testing reasons, I need them to be in the future.
- Object1) StartTime = 7/2/2022 @ 8:00amEST
- Object2) StartTime = 7/2/2022 @ 9:00amEST
- Object3) StartTime = 7/4/2022 @ 3:00pmEST
- Object4) StartTime = 7/4/2022 @ 3:30pmEST
- Object5) StartTime = 7/5/2022 @ 10:00amEST
- ... etc.
I need to shuffle these times to be based on a date in the future, so much as even DateTime.Now.AddDays(1);
I've tried multiple times, but always botch things like having the wrong month, or ending up with a datetime on the 32nd.
The output of this method would take the dates and revise as so:
- Object1) StartTime = 11/22/2022 @ 8:00amEST
- Object2) StartTime = 11/22/2022 @ 9:00amEST
- Object3) StartTime = 11/24/2022 @ 3:00pmEST
- Object4) StartTime = 11/24/2022 @ 3:30pmEST
- Object5) StartTime = 11/25/2022 @ 10:00amEST
DateTime CreateDateFromTime(int year, int month, int day, DateTime time)
{
return new DateTime(year, month, day, time.Hour, time.Minute, 0);
}
for (int i = 0; i < evt.Sessions.Count; i )
{
Session session = evt.Sessions[i];
if (session.StartDate.HasValue)
{
DateTime currentSessionStartDate = session.StartDate.Value;
DateTime currentSessionEndDate = session.EndDate.Value;
if (earliestSessionDay == 0) { earliestSessionDay = currentSessionStartDate.Day; }
int innerOffset = currentSessionStartDate.Day - earliestSessionDay;
int offset = DateTime.Now.Day - earliestSessionDay;
session.StartDate = CreateDateFromTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day offset innerOffset 5, currentSessionStartDate);
session.EndDate = CreateDateFromTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day offset innerOffset 5, currentSessionEndDate);
}
}
I would have mocked dates, but again, for testing reasons, the test users want to use data they are familiar with so we end up reusing these objects, thus necessitating this weird date shift thing.
CodePudding user response:
This does what I think you need:
DateTime[] dates = new []
{
new DateTime(2022, 7, 2, 8, 0, 0),
new DateTime(2022, 7, 2, 9, 0, 0),
new DateTime(2022, 7, 2, 15, 0, 0),
};
DateTime minimum = dates.Min();
TimeSpan delta = DateTime.Now.AddDays(1.0).Subtract(minimum);
DateTime[] forwarded =
dates.Select(d => d.Add(delta)).ToArray();
If you want to preserve the times, then use .Date
like this:
DateTime minimum = dates.Min().Date;
TimeSpan delta = DateTime.Now.Date.AddDays(1.0).Subtract(minimum);