How to convert DateTime to Integer and check the difference? - vb.net

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.

Related

String value wrongly converted to datetime using vb.net

So I have this datetime value of 9.3.2016 18:56:12, by using datetime.parse, I can get the values but instead of getting '3' as the month, it takes '9' as month and '3' as day which is incorrect.
dim d1 as string = "9.3.2016 18:56:12"
dim d2 as datetime = datetime.parse(d1, CultureInfo.InvariantCulture)
I don't want to use datetime.parseExact because I'm having more than 1 value in the database.
Please help :( thank you!
Since you current culture appears to interpret dates in the way you expect you could simply do this,
Dim dateString = "9.3.2016 18:56:12"
Dim dateValue = DateTime.Parse(dateString)
By not specifying the InvariantCulture, you instruct DateTime.Parse to use the current culture which, in your case, interprets the date string correctly.
Sorry I've got the solution.
dim d2 as datetime = convert.todatetime(d1)

Issue in Converting string to Date in VBA

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

Date format from database gets wrong date in vb.net

I'm taking in data from a SQL database and now I'm trying to convert the data to a proper date variable in VB.NET but I don't get the proper format.
Data from the database:
28-FEB-14 01:00:00:0
28-FEB-14 13:00:00:0
The date I get when trying to convert it:
2028-02-14
2028-02-14 12:00:00
The code that is doing the conversion:
Dim theDate As DateTime
Dim try1 As Date
For i As Integer = 0 To batchCount - 1
If Date.TryParse(dv(i)(0), theDate) = True Then
try1 = theDate.ToUniversalTime()
End If
Would appreciate all the help I can get.
Firstly, date values in your database should be date types, so when you read them in, you read them into a Date type variable.
If you then want to format that date you can use a ToString overload
Dim theDate as DateTime = dr.item("date")
Debug.Writeline(theDate.ToString("yyyy-MM-dd")
Secondly if the date is being stored as a string field in the database (you should not do this but you may have no control over this) it should be in a specific format, so you can use ParseExact to convert this into a date:
Dim dateString As String
dateString = DateTime.ParseExact(dr.item("Date"), "dd-MMM-yy HH:mm:ss.f", CultureInfo.CurrentCulture)

Is there a way to compare Date objects ignoring the time?

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

How to get a date field from MM/dd/yyyy to yyyy/MM/dd in vb.net

I need to get a date field from MM/dd/yyyy to yyyy/MM/dd in vb.net but it should still be a date field afterward so that I can match it against a date in a database.
At the moment all I'm managing to do is to change it to a string in that format.
I tried this type of code which also did not work.
DateTime.Parse(yourDataAsAString).ToString("yyyy-MM-dd")
fromDeString = String.Format("{0:yyyy/MM/dd}", aDate)
fromDate = Format("{0:yyyy/MM/dd}", aDate)
Any help would be much apreciated, thanks
You're not understanding that a date object does not store the digits in any particular format. The only way to get the digits formatted in the order you want is to convert it to a string. Why do you need to compare them in a particular format? A date is a date no matter how it is formatted. 12/15/78 == 1978/12/15.
If you are not able to compare dates from the DB against a date object in VB, it is likely that the date you are comparing to in the database is being returned to you in string format, in which case you should covert it to a date object for comparison.
Dim sDate As String = "2009/12/15" 'Get the date from the database and store it as a string
Dim dDate As New Date(2009, 12, 15) 'Your date object, set to whatever date you want to compare against
Select Case Date.Compare(dDate, Date.Parse(sDate))
Case 0
'The dates are equal
Case Is > 0
'The date in the database is less
Case Is < 0
'The date in the database is greater
End Select
Here's a sample module demonstrating the functionality you desire.
Imports System.Globalization
Module Module1
Sub Main()
Dim culture As New CultureInfo("en-us", True)
Dim mmDDyy As String = "10/23/2009"
Dim realDate As Date = Date.ParseExact(mmDDyy, "mm/dd/yyyy", culture)
Dim yyMMdd As String = realDate.ToString("yyyy/MM/dd")
End Sub
End Module
Hope this helps.
Kind Regards
Noel
Your second should actually work. Instead just try:
dim chislo as date = date.now dim message As String = $"
Today`s Date: {String.Format("{0:dddd, dd/MM/yyyy}", Chislo)} "
MsgBox(message)