Share via


How to add AM or PM to Datetime?

Question

Monday, December 13, 2010 9:16 AM

Initial Datetime:

a= 12/1/2010 12:00:00 AM

I want to make it 12/1/2010 12:05:00 PM and then i want to get the difference.

a=12/1/2010 12:00:00 AM

b=12/5/2010 12:05:00 PM

diff=b-a

How can i do this?

All replies (8)

Monday, December 13, 2010 12:17 PM âś…Answered

Here you go:

      string a = "12/1/2010 12:00:00 PM";
      string b = "12/5/2010 12:05:00 PM";

      DateTime aDate = Convert.ToDateTime(a);
      DateTime bDate = Convert.ToDateTime(b);

      TimeSpan diff = bDate - aDate;

Noam B.

Do not Forget to Vote as Answer/Helpful, please. It encourages us to help you...


Monday, December 13, 2010 9:36 AM

System.TimeSpan diff1 = date2.Subtract(date1);

As Given here http://msdn.microsoft.com/en-us/library/8ysw4sby.aspx


Monday, December 13, 2010 10:02 AM

I know about subtract.

But how can i add PM or AM consideration?


Monday, December 13, 2010 10:24 AM

Initial Datetime:

a= 12/1/2010 12:00:00 AM

I want to make it 12/1/2010 12:05:00 PM and then i want to get the difference.

a=12/1/2010 12:00:00 AM

b=12/5/2010 12:05:00 PM

diff=b-a

How can i do this?

What do you mean by I want to make it PM. Here all I can see is you have made it PM and added 5 mins.

If you just make it PM the difference is always 12 hours. Please give a real life scenario.


Monday, December 13, 2010 10:32 AM

DateTime a = new DateTime(2010, 12, 1, 0, 0, 0);
DateTime b = new DateTime(2010, 12, 5, 12, 5, 0);
TimeSpan diff = b - a;

Monday, December 13, 2010 10:53 AM

vijaykamat,

Datetime a=new DateTime(2010,12,2,0,0,0);

Datetime a=new DateTime(2010,12,2,0,0,0);

TimeSpan diff=b-a;

 

This is correct but i wanted this.

Datetime a=new DateTime(2010,12,2,0,0,0,AM);

Datetime a=new DateTime(2010,12,2,0,0,0,PM);

TimeSpan diff=b-a;

 

How can i add PM to a DateTime object?

Or how can i add PM or AM consideration to a DateTime object?


Monday, December 13, 2010 1:22 PM

"AM" and "PM" are a notation. It belongs to the display representation of a time, not its value. The closest you have when dealing with the real data is to use AddHours(12) to turn an AM time to PM.


Monday, December 13, 2010 2:44 PM

Thanks Louis.fr and all.