Is there a way to compare two dates (which include time) ignoring the time?
I have a 1/1/2009 8:00am and 1/1/2009 9:00am and I just want to know if it is the same day, without any care to what time it is.
I know I can convert the date and compare the strings, but is there another way?
Yes, you can use the .Date property of the Date object you are using.
dim originalDate as DateTime
originalDate = '(get your date for comparison)
if originalDate.Date = Datetime.now.date then
'it happened today.
end if
dim Date1 = firstdate.ToShortDateString
dim Date2 = seconddate.ToShortDateString
if (Date1 = Date2) then
'Dates Match!
return true;
else return false
Related
I need to write a function which will convert 2 string parameters to dates and
return true/false after comparing the dates.
I have tried to implement this requirment by writing below mentioned code
Function CompareDate(StringDate1 As String, StringDate2 As String) As Boolean
Dim Date1 As Date
Dim Date2 As Date
Date1 = CDate(StringDate1)
Date2 = CDate(StringDate2)
If Date1 > Date2 Then
CompareDate = True
Else
CompareDate = False
End If
End Function
Dim test As Boolean
test = CompareDate("03-Mar-2016 02:43 PST", "01-Mar-2016 11:33 PST")
But I am getting "Type Mismatch" error at this line Date1 = CDate(StringDate1).
Any idea what needs to be modified to fix the issue.
Note : My function also needs to consider time and time zone while comparing dates.
try cdate(split(StringDate1," ")(0)) and (1) will give you the time to check also, when date1=date2? or you can replace the PST part
The parse problem is with the presence of a timezone. There are a lot of ways to manage this date time depending on what your endgame is but the most straightforward is just to drop off the timezone and let CDATE parse it. In the following code I assume that a) all of your times are in PST and b) there is a timezone on the end of every date. If these assumptions are wrong, modifications are necessary. If essential, managing multiple time zones could be done by converting everything to one time zone and, if desired, tracking what time zone it came from. But I don't know of any standard VBA module that knows the time zones so that would need an array from you.
Function CompareDate(strDate1 As String, strDate2 As String) As Boolean
Dim Date1 As Date
Dim Date2 As Date
Date1 = CDate(Left(strDate1, InStrRev(strDate1, " ")))
Date2 = CDate(Left(strDate2, InStrRev(strDate2, " ")))
CompareDate = (Date1 > Date2)
End Function
Maybe you could construct the timezone vs UTC offset array from the table here but I don't have time to process it right now. Pretty straightforward once you construct that array.
i think it would help if you formatted the date before doing CDate.
dateX = format(StringDate1, "mm/dd/yyyy")
You can also try somethign like this
dateX = cdate(format(stringdate1,"mm/dd/yyyy") - see that how works.
I don't have anythignt to test it with. If worst comes to worst, instead of passing the StringDate1 as string, pass it as Date and should be all set then. No need to do CDate in that case.
Function CompareDate(StringDate1 As Date, StringDate2 As Date) As Boolean
and Wherever you call this function CompareDate....do CDate then.. as such...
Call CompareDates(cdate(stringdate1), cdate(stringdate2))
The date portion gives you an integer value referring to the date, and the time portion gives you a fractional value for the time. So just add the two such as (using #Nathan_Sav code):
cdate(split(StringDate1," ")(0)) + cdate(split(StringDate1," ")(1))
Give this a try:
Function CompareDate(StringDate1 As String, StringDate2 As String) As Boolean
Dim Date1, Date2
Date1 = Split(StringDate1, " ")
Date2 = Split(StringDate2, " ")
CompareDate = IIf(DateDiff("d", Date1(0), Date2(0) > 0 And DateDiff("n", Date1(1), Date2(1)) > 0), True, False)
End Function
For the following code, I am receiving this error: "Conversion from String "10/22.2014 12:00:00 A10" to type 'Date' is not valid." Note - in comparison to the code, below - the error message's conversion of AM to A10.
What I Am Trying To Do
I am trying to give a user the ability to query a database for transactions that occurred, today. In order to do this, I need to specify the timestamp for the transaction, i.e. MM/dd/yyyy timestamp. I have consulted the MSDN documentation; however, am unable to get my code to function, properly.
By default, Date objects appear to drop their timestamp (this may be a result of the code I am working with, e.g. the casting); therefore, when specifying a date range of "today" (Today's Data - Today's Date), I am left with the default behaviour of the object: Today's Date 12:00:00 AM - Today's Date 12:00:00 AM. Regardless as to why this is happening, this is the problem with which I am left.
The objective: MM/dd/yyyy 12:00:00 AM - MM/dd/yy 11:59:59 PM (the day being the same).
My goal is to force a particular timestamp for a Date object (note this is not a DateTime object). By specifyiong the time range, I am able to grab all data from a database for today.
What I've Got
Below, is the code and, below that, the description (I've tried to condense the code as much as possible). You'll also note that this is only half of the code, i.e. the FromDate portion (presumably the format can be replicated for the ToDate:
Public Shared Function ToFromDate(ByVal aValue As Object) As Date
Dim Result As Date
Try
Result = CDate(aValue)
Catch ex As Exception
Result = Now
End Try
Result = CDate(String.Format("{0:MM/dd/yyyy 12:00:00 AM}", Result))
Return Result
End Function
The above code takes as an argument a DateTime, e.g. 10\10\2010 12:15:63 PM (and, for the purposes of my problem, the timestamp is included). Again, I am trying to take that Date with timestamp and change the time. Result receives aValue, casting the object as Date to "ensure" it is a date.
After Result receives a value (as when declaring a Date it is initialized to #12:00:00 AM#, interestingly enough), I attempt to CDate() a formatted String object. I have also attempted to remove the second cast, yet still receive the same error (the Result = CDate(String...) line throwing the error).
Question(s)
The main question: how do I appropriately cast a date to include a specified time?
The second, trivial question: what's with the # surrounding the Date? Is this a SQL 'thing'?
Here's my work around for the above not working, so far:
Dim Result As Date
Dim DateString As String = CStr(aValue)
Dim TestDateString As String = DateString.Substring(0, DateString.IndexOf("/"))
Dim NewDateString As String = ""
If TestDateString.Length = 2 Then
NewDateString = DateString.Substring(0, 10)
Else
NewDateString = DateString.Substring(0, 8)
End If
NewDateString = NewDateString + " 12:00:00 AM"
NewDateString = CObj("#" + NewDateString + "#")
Result = CDate(NewDateString)
Return Result
First, a date is the number of ticks since a point in time. Formatting it to a string and then converting to a date does nothing but spin the wheels of your CPU.
Because of culture issues, you should always create dates using NEW DATE(?,?,?,etc)
Second, the # is a vb6 way of creating dates (and MS Access) that is there for backwards compatibility.
Third, If you have a date (no time or as of midnight), and you want it to be as of say 6AM, you simply add the time you want. IE:
Dim d As Date = New Date(2014,1,1)
d = d.AddHours(6)
'Result: d = 1/1/2014 6:00:00 AM
Lastly, if you have a date and time and you want to remove the time, there are many ways but this is the one I like:
Dim d As Date = Now
d = New Date(d.Year, d.Month, d.Day)
How can I compare the last characters using of month, day, and year or the completedate rather than using datetime, Example case is Textbox3 is greater than textbox9 because Textbox3 day = 26 and textbox9 day = 25.
Mycode:
'in my case I have 2 Textbox.
'Date format: hh.mm MM/DD/YYYY
'Textbox3= 02.02 03/26/2014
'TextBox9= 21.01 03/25/2014
If Val(Strings.Left(TextBox9.Text.Trim, 5)) < Val(Strings.Left(Textbox3 .Text.Trim, 5))Then
TimeError.ShowDialog()
End If
Really, the fastest, most reliable, and most effective way to do this is to parse the values into a DateTime. And taking a step back from there, the fastest, most effective way to get a date time from a textbox is to use a DateTimePicker control.
But if that's not an option, we can build on the code I gave you last time:
Dim temp1() As String = Textbox3.Text.Trim().Split(" .".ToCharArray())
Dim temp2() As String = Textbox9.Text.Trim().Split(" .".ToCharArray())
If DateTime.Parse(temp2(2)) < DateTime.Parse(temp1(2)) Then
TimeError.ShowDialog()
End If
I'll add that you probably want to also have code to compare the time values in the case where the date portions are equal. Given this as a starting point, you should be able to write that code on your own.
in vb.net you can comopare dates like this:
dim date1 as date = cdate(Textbox1.text)
dim date2 as date = Date.now()
if date1.date=date2.date then ....
and months like this
if date1.month=date2.month then ...
I'm trying to compare the difference between two times in the day. I'm getting time in UTC format. Do I have to convert DateTime to integer in order to get the difference and if yes how?
This is my code
Dim ct As DateTime = DateTime.UtcNow
Dim int_ct As Integer = Convert.ToInt32(ct)
MsgBox(ct + " | " + int_ct)
If (System.IO.File.Exists(System.IO.Path.GetTempPath.ToString + "\tempfile.data")) Then
Dim time As DateTime = System.IO.File.ReadAllText(System.IO.Path.GetTempPath.ToString + "\tempfile.data")
Dim int_time As Integer = Convert.ToInt32(time)
If ((int_ct - unlockedtime) < int_time) Then 'unlockedtime is Int variable
Return False
Else
Return True
End If
End If
You don't need to do any timezone conversion, just make sure that both date/time values are in the same timezone when you capture them (though I suppose it might be wise use to UtcNow in case the system timezone changes in-between your two measurements.
You don't need to convert values to Int32 to get the difference, just use the DateTime.Subtract method:
Dim old As DateTime = GetOldDateTime()
Dim now As DateTime = DateTime.UtcNow
Dim diff As TimeSpan = now.Subtract( old )
If diff.TotalSeconds > someSecondsValue Then
DoSomething()
End If
Have you tried Datetime.Compare(dt1,dt2)? Depending on how much detail you need this might work for you.
Here is more information on the function:
http://msdn.microsoft.com/en-us/library/system.datetime.compare.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1
As Dai said you may want to compare difference, but if you just want the date difference you can use the following:
DateDiff(DateInterval.Minute, Date1, date2)
This returns the difference as an integer, you can set whatever date interval you require as the firt parameter.
This issue stems from an accounting package that spits out text-based reports with rows of data having invalid dates, like February 31st or September 31st.
The reports are formatted with spaces and mono-spaced fonts. My goal is to parse out the data needed and generate a more formal report (SSRS).
What I am interested in fixing is the situation where a date is invalid and can't be directly converted into a DateTime struct. The date format from the report is MMM-dd-yy (e.g. Feb-30-10). I would like to convert the invalid date strings into the closest valid DateTime in the same month before showing them in the formal report. I've seen this done two ways in my time as a developer, both very poorly, so I want to come up with a simple way of doing it (if there isn't a built-in way I don't know about).
The first bad method I've seen(I can't believe I'm even showing you!):
Dim month As Integer = <Parse out the month from the bad date string>
Dim day As Integer = <Parse out the day from the bad date string>
Dim year As Integer = <Parse out the year from the bad date string>
Dim validDate As DateTime
While True
Try
validDate = New DateTime(year, month, day)
Exit While
Catch ex As ArgumentOutOfRangeException
day -= 1
End Try
End While
I hope I don't have to explain what I don't like about that method.
The second bad method:
Dim badDateString As String = <Current date string from text report>
Dim validDate As DateTime
If DateTime.TryParseExact(badDateString, "MMM-dd-yy", Nothing, Globalization.DateTimeStyles.None, validDate) Then
Return validDate
End If
badDateString = badDateString.Replace("31", "30")
' ... try the parse again, if still not valid, replace "30" with "29"
' ... try the parse again, if still not valid, replace "29" with "28"
These make for some sad code and me a sad developer.
I've been trying to think of a more efficient way of doing this. Any ideas?
EDIT:
I found a solution and have posted it, but I liked Guffa's answer more.
Reading the previous code, the last code is pretty much what I was going to suggest.
Here is a variation of the code:
Return New DateTime(year, month, Math.Min(day, DateTime.DaysInMonth(year, month)))
Here was the solution I discovered before Guffa answered. It takes the parts of a date (month, day, year), uses the number of days in that particular month/year combination to validate the incoming day part, and adjusts if necessary before constructing a new DateTime.
Dim validDate As DateTime
Dim dayMax As Integer = DateTime.DaysInMonth(year, month)
Dim newDay = day
If day > dayMax OrElse day < 1 Then
newDay = dayMax
End If
validDate = new DateTime(year, month, newDay)
Return validDate