date conversion question

  • Thread starter Thread starter WIlliam Barnes
  • Start date Start date
W

WIlliam Barnes

Why does this code result in a False result?

Public Sub TimeTest()

Dim dte As Date
Dim lng As Long

dte = Now
lng = CLng(dte)

Debug.Print (dte = CDate(lng))

End Sub
 
Because Now includes the fraction which represents the time

--

Kind Regards,

Niek Otten

Microsoft MVP - Excel
 
A date also has decimal places that represent the time.
By converting it to a LONG, the value after the decimal point disappears.
When you test "dte" against "lng" you are comparing, say, 38047.25 against
38047.
By converting "lng" back to a date you get 38047, that is to say 29/02/2004
00:00:00 (or midnight).

That is to say, by losing the decimal places in the first conversion you
have created a different figure, and so when you do the final comparison,
you get False.

--
Regards
Andy Wiggins
www.BygSoftware.com
Home of "Save and BackUp",
"The Excel Auditor" and "Byg Tools for VBA"
 
Somehow I thought that dates were represented as integral values. When I
cast it to a Double it works as expected. Thanks.
 
William,

The reason is because Now returns the date and time, so you get something
like 29/02/2004 18:45:32, whereas CDate(lng) returns a pure date, like
29/02/2004. They are not the same, so you get False.

--

HTH

Bob Phillips
... looking out across Poole Harbour to the Purbecks
(remove nothere from the email address if mailing direct)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top