-2

Is it possible to get the timespan of A and B, where A(MM-dd-yyyy) = 10-06-2015 23:45 and B = 9:00 AM. The given format of data are exactly what it is on this post. I guess am having trouble on formatting, no coded work yet.

I have other question that may linked to the first, is if(A>B) possible ? where A(MM-dd-yyyy) = 10-06-2015 23:45 and B = 9:00 AM. Does comparing the two data possible ?

pruuylan
  • 86
  • 1
  • 1
  • 10
  • Are you asking for the *difference* between A and B? What if B is on a different date than A? What if it's already passed? Would you expect a negative value, or the next day? Do you need it to consider daylight saving time, and if so - in the local time zone or in an arbitrary time zone? Please edit your question to be more specific. A few examples of input and expected output would be helpful. – Matt Johnson-Pint Oct 19 '15 at 05:14
  • thank you for the tip, sir. – pruuylan Oct 19 '15 at 05:53

2 Answers2

1
DateTime a = DateTime.ParseExact( "10-06-2015 23:45"  , "MM-dd-yyyy HH:mm"   , CultureInfo.InvariantCulture );
DateTime b = DateTime.ParseExact( "10-06-2015 9:00 AM", "MM-dd-yyyy hh:mm tt", CultureInfo.InvariantCulture );
TimeSpan difference = a - b;

If you only know b by the time-of-day, then this works:

DateTime b = DateTime.ParseExact( "9:00 AM" "hh:mm tt", CultureInfo.InvariantCulture );
b = a.Date.Add( b.TimeOfDay );

TimeSpan difference = a - b;

You say you're using DateTimePicker, in which case:

DateTime a = dateTimePicker1.Value;
DateTime b = a.Date.Add( dateTimePicker2.TimeOfDay );
TimeSpan difference = a - b;
Dai
  • 141,631
  • 28
  • 261
  • 374
  • but, my B's format is fixed as 9:00 AM from DateTime Picker – pruuylan Oct 19 '15 at 04:53
  • @SuperPruuylan my apologies. I have expanded my answer to include that scenario. – Dai Oct 19 '15 at 04:57
  • 1
    @SuperPruuylan That said, if you're using `DateTimePicker` then you don't need `ParseExact` at all, you can use the value directly. I'll update my answer. – Dai Oct 19 '15 at 04:58
  • let me ask you something, my A = `10-06-2015 23:45` and B = `9:00 AM`. Is it possible, sir, to do this `if(A >B)` ? sorry, I can't tag yah name – pruuylan Oct 19 '15 at 05:07
  • @SuperPruuylan You can, but `B` must consist of a date and time value, not just a time value. Look at my code to see how I'm adding the date component of `a` to the time component of the time-of-day value. – Dai Oct 19 '15 at 05:47
0

Use TimeOfDay for this.

This will also help.

Example: Define your times like this.

startDate='10-06-2015' startTime=10-06-2015 23:45:00 AM'

TimeSpan ts = startTime.TimeOfDay;
DateTime dt = startDate.Add(ts);
MusicLovingIndianGirl
  • 5,909
  • 9
  • 34
  • 65