DateTime manipulation

  • Thread starter Thread starter Patrick B
  • Start date Start date
P

Patrick B

Say I have three DateTime variables:

DateTime A;
DateTime B;
DateTime C;

How can I assign to C just the date part of A and just the time part of B?

Something like this...

C = A.Date + B.TimeOfDay;

Except that isn't it.
 
Patrick B said:
Say I have three DateTime variables:

DateTime A;
DateTime B;
DateTime C;

How can I assign to C just the date part of A and just the time part of B?

Something like this...

C = A.Date + B.TimeOfDay;

Except that isn't it.

I ended up writing a utility method which did something like this -
it's not hard to write once and then use repeatedly. Basically use the
form of the DateTime constructor which takes everything you want, and
take some parts from A and some parts from B.
 
Hi,

Another solution could be take the data part of A

a.Date

and the time components of B

b.Second , b.Hour , b.Minute

That should work

Cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
 
Or, if we wanted to be really nifty:

// Get the date and time.
DateTime now = DateTime.Now();

// Get the date portion, and the time.
DateTime date = now.Date;
TimeSpan time = now.TimeOfDay;

Hope this helps.

--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Ignacio Machin ( .NET/ C# MVP ) said:
Hi,

Another solution could be take the data part of A

a.Date

and the time components of B

b.Second , b.Hour , b.Minute

That should work

Cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
 
Ahh, I get you...

DateTime C = new DateTime(A.Year, A.Month, A.Day, B.Hour, B.Minute,
B.Second);

Thanks, that works.
 
Patrick said:
How can I assign to C just the date part of A and just the time part of B?
Use the DateTime constructor with Year, Month and Day from DateTime a
and Hour, Minute and Second from DateTime b.

DateTime a=new DateTime(2005,01,04);
DateTime b=DateTime.Now;
DateTime c=new DateTime(a.Year,a.Month,a.Day,b.Hour,b.Minute,b.Second);

Anders Norås
http://dotnetjunkies.com/weblog/anoras/
 
Patrick B said:
Ahh, I get you...

DateTime C = new DateTime(A.Year, A.Month, A.Day, B.Hour, B.Minute,
B.Second);

Thanks, that works.

Goodo - but actually, looking at your original post, I don't see why
that shouldn't work. For instance:

using System;

class Test
{
static void Main()
{
DateTime now = DateTime.Now;
DateTime yesterday = DateTime.Today.AddDays(-1);
DateTime thisTimeYesterday = yesterday.Date+now.TimeOfDay;

Console.WriteLine(thisTimeYesterday);
}
}
 
Try This

DateTime A = DateTime.Now;

DateTime B = DateTime.Now.Add(-1);

DateTime C = A.Date.AddTicks(B.TimeOfDay.Ticks);



Ciaran
 
Back
Top