Solved

Comparing two dates dimmed as objects in VB.NET

Posted on 2011-03-05
14
693 Views
Last Modified: 2012-08-14
Hello Experts -

I am trying to comparing two dates in VB.NET, but I can't get the code to work. Here is the code snippet:

Dim prevdatetime As Object
Dim prevtime As Object
Dim testtime As Object

prevdatetime = #2/28/2011 8:45:00 PM#
prevtime = prevdatetime.ToLongTimeString      (Gives me 8:45:00 PM)
testtime = #12:00:00 PM#

If CDate(prevtime) < CDate(testtime) Then
             blah, blah, blah...                                  (The code doesn't get here.)
End If

Got any idea what I'm doing wrong?
0
Comment
Question by:gbmcneil
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 3
  • 2
  • +3
14 Comments
 
LVL 16

Accepted Solution

by:
sjklein42 earned 63 total points
ID: 35045019
Not to state the obvious, but isn't 12:00:00PM (ie. noon) earlier than 8:4:00PM (at night) so the test is expected to fail since prevtime (at night) is > testtime (noon)?
0
 
LVL 10

Expert Comment

by:Jacco
ID: 35045191
Tip: Never do unnessary conversions from text to date and reverse, only explicitly do this when you get the data from its source or write it to its destination. (So best not to use CDate(stringVar))

12:00PM is equal to the smallest time 0:00AM (you might use "11:59:999 PM" for upper bound, but this will essentially always render true)

Another approach in stead of working with DateTimes with "zero" dates is to use them with an equal date (or in case of 12:00PM one day ahead)

Regards, Jacco

0
 
LVL 16

Expert Comment

by:sjklein42
ID: 35045270
0
How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

 
LVL 10

Expert Comment

by:Jacco
ID: 35045847
my bad :-)
0
 
LVL 9

Expert Comment

by:Orcbighter
ID: 35045966
Your problem is that TestTime is a Time and not a date.
Its the same structure but the year month and day are set to min values.
To make it work, and I assume that since you were comparing a time, you were assuming that the date was Today, You should set the testTime variable to Now, then modify the time to what you want, then do the comparison.
Or, if you really only want to compare times, zero-out the year, month and day values.
See an example in the code snippet below:

Dim prevdate As DateTime = #2/28/2011 8:45:00 PM#
        Dim testdate As DateTime = Now

        'if current time is 11.30 PM, and you want 12pm (midnight, ie 0 on 24-hour scale) then just modify the hours
        testdate.AddHours(1)
        testdate.AddMinutes(30)

        If DateTime.Compare(prevdate, testdate) > 0 Then
            Console.WriteLine("prevdate > testdate")
        ElseIf DateTime.Compare(prevdate, testdate) = 0 Then
            Console.WriteLine("prevdate == testdate")
        ElseIf DateTime.Compare(prevdate, testdate) < 0 Then
            Console.WriteLine("prevdate < testdate")
        End If

Open in new window

0
 

Author Comment

by:gbmcneil
ID: 35047134
My eight lines of code certainly took a bashing. Does this approach represent an improvement to you guys?

Dim prevdatetime As DateTime
Dim prevtime As DateTime
Dim testtime As DateTime

prevdatetime = #2/28/2011 8:45:00 PM#
prevtime = CDate(prevdatetime.ToLongTimeString)      '(Gives me 8:45:00 PM)
testtime = #11:59:59 PM#

If prevtime <= testtime Then
                'blah, blah, blah...                                            '(Stop triggered)
                Stop
End If

By the way, it never occurred to me that 12:00 midnight was 12:00 AM. It sounds illogical. Also, the test may sound nonsensical. That is because it is taken out of context and is considerably more complex in real life. I'm just trying to simplify things for discussion.
0
 
LVL 16

Expert Comment

by:sjklein42
ID: 35047194
Looks a little odd to me.  How does testtime string get converted to a DateTime?  Is there an implied conversion?  Orcbighter, what do you say?

Question is, does it work?

The logic I use to explain why noon should be 12PM is that 12:00:01 after noon is clearly PM, and truncating the seconds or minutes from the display should not change it from PM to AM.
0
 
LVL 86

Assisted Solution

by:Mike Tomlinson
Mike Tomlinson earned 62 total points
ID: 35047204
Just to show a different method, I would do:
Dim prevdatetime As DateTime = #2/28/2011 8:45:00 PM#

        If prevdatetime.TimeOfDay <= New TimeSpan(23, 59, 59) Then ' #11:59:59 PM#
            'blah, blah, blah...                                            '(Stop triggered)
            MessageBox.Show("Stop: Less Than or Equal to 11:59:49 PM")
        End If

Open in new window


*But* all TIMES are less than 11:59:59 PM by definition.  So the check is pointless...
0
 
LVL 19

Expert Comment

by:Shahan Ayyub
ID: 35047257
Hi!

First thing you need to do is to use CORRECT DATA TYPE.

like, change this:
        Dim prevdatetime As Object
        Dim prevtime As Object
        Dim testtime As Object

to
        Dim prevdatetime As DateTime
        Dim prevtime As String
        Dim testtime As DateTime

then final code should look like this:
     
   Dim prevdatetime As DateTime
        Dim prevtime As String
        Dim testtime As DateTime

        prevdatetime = #2/28/2011 8:45:00 PM#
        prevtime = prevdatetime.ToLongTimeString      '(Gives me 8:45:00 PM)
        testtime = #12:00:00 AM#

        If CDate(prevtime) < testtime Then
            ' blah, blah, blah...                                  (The code doesn't get here.)
        End If

Open in new window

0
 

Author Comment

by:gbmcneil
ID: 35047338
Gee, guys you're making me feel hurt. Like I should have gone into the landscaping business or something.

You're saying that a DateTime variable has got to have both a date and a time. A variable that has only one of these elements doesn't qualify. So, you can't compare dates to dates and times to times unless you've got the whole enchilada.

So, you have to use attributes like TimeOfDay to make comparisons. Okay. I can appreciate the 12:00 AM midnight argument too.

By the way, the code does work - but, it may be sheer luck.

0
 

Author Comment

by:gbmcneil
ID: 35047496
Okay. If variable "testtime" can be type DateTime, then why can't variable "prevtime" be type DateTime too?  (NOTE: And, iif testtime only indicates a time, then someone other than me says it can be dimmed as DateTime.)

In one of my examples I suggested:

Dim prevtime As DateTime
prevtime = CDate(prevdatetime.ToLongTimeString)

...and then continued to make the comparison:

If prevtime <= testtime Then
                'blah, blah, blah...
End If

That is the only difference between my program snippet and Shahan Developer's.  

But, the consensus was that this was wrong. I think I'm confused. Hold up on that rake!


0
 
LVL 19

Expert Comment

by:Shahan Ayyub
ID: 35047665
Hi! @gbmcneil

Both are the same things, but the difference is the line, where operations performed. I didn't see the post that you have almost similar of my post because I didn't refreshed this page and posted you the code.

>>>If variable "testtime" can be type DateTime, then why can't variable "prevtime" be type DateTime too?

In your original question, "prevdatetime.ToLongTimeString" returns "string" so i suggested it to declare as a type "string". Everyone who is providing you a code can be an alternative of your requirement, it doesn't mean to hurt you. You can ask for clarification from that expert that why they suggested it.

My apologies if you are confused from my comment.
0
 

Author Comment

by:gbmcneil
ID: 35048047
My comments addressed the revised code I presented 8 panels down from the top of this question.

What you seem to be suggesting is that "there is more than one way to slice a tomato". And, there very well may be.

But, I think that Idle Mind opines that there is no need to create unnecessary variables when you can just use the "attributes" of the first variable presented that was given the type DateTime. In my example, this was prevdatetime. Idle say if you want the date alone, say prevdatetime.Date. Or if you want the time, it can be had by using prevdatetime.TimeOfDay.

Other than the 12:00 AM midnight brew-hah-hah, I think that this is what this question boils down to.
0
 

Author Closing Comment

by:gbmcneil
ID: 35048068
A great discussion. I learned a lot. Too bad I don't have more points to hand out. All the responses were great and I appreciate them immensely.
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…

734 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question