How to compare two datetime value instead of string using VB.Net - vb.net

How to compare two datetime values?
For example as per below condition, I have FDatetimes value is string coming (i.e 2021-06-21 17:00:30Z) from database and SDatetimes value should be Datetime.UtcNow. So my requirement is both left and right side always compare with datetime instead of string.
Also I have tried to use Convert.ToDateTime(FDatetimes). But there is one issue here. Whenever I have used the above function, That time the time is getting changed to 2021-06-21 10:00:30Z. My main aim is to compare both field value as DateTime instead of String. Please help in VB.Net
If FDatetimes < SDatetimes Then
'My logic
End If

So to resolve DST issues I did this (which I ran at 9:20AM local, 14:20 UTC on 23 Jun 2021)
Dim SDatetimes As DateTime = DateTime.UtcNow
Dim FDatetimes As String = "2021-06-23 15:20:30Z"
Dim FDT As DateTime = DateTime.ParseExact(FDatetimes,
"yyyy-MM-dd HH:mm:ssZ",
Globalization.CultureInfo.InvariantCulture,
Globalization.DateTimeStyles.AdjustToUniversal Or
Globalization.DateTimeStyles.AssumeUniversal)
Debug.WriteLine(SDatetimes.ToString)
Debug.WriteLine(FDT.ToString)
If FDT < SDatetimes Then
'My logic
Stop
End If

Related

What is the date format to convert from string to date

I have below code to get StringToDate as 04/29/2019, but when use CDate function it's giving me #4/29/2019 12:00:00 AM# value. which date format i have to use to get 04/29/2019
Dim StringToDate As Date
Dim strNewDate As String = "04/29/2019"
StringToDate = CDate(strNewDate)
You could use DateTime.TryParse
Dim MyDate As DateTime = Nothing
Dim strNewDate As String = "04/29/2019"
DateTime.TryParse(strNewDate, MyDate)
Edit (misread your question)-
A DateTime holds value and not String. To get what you asking after parsing the date you would need to convert it back to a string with a format method or use the following:
MyDate.ToShortDateString
The way a date is represented is by what the region settings of your OS have setup.
For example, if you were to open the region settings in Control Panel you would find a format for Short Date which by what you're describing is probably M/d/yyyy. Inside the dropdown are other formats you can set and if you were to set it to MM/dd/yyyy you would see that your same code would now display 04/29/2019. But Don't Do This as it only affects your machine. Instead, understand that a date is only number, and you can control how it is displayed, the same way Windows just did from my example. A perfect example of this is that you could set a DateTime variable in many different ways. Here's a few:
Dim dt1 As DateTime = #2019-12-14#
Dim dt2 As DateTime = #1/08/2019#
Dim dt3 As DateTime = #03/03/2019#
Dim dt4 As DateTime = #4/4/2019#
The results would be
12/14/2019 12:00:00 AM
1/8/2019 12:00:00 AM
3/3/2019 12:00:00 AM
4/4/2019 12:00:00 AM
because that is how windows is set up to show me a DateTime as a string.
When you want to display this date to the user in a different format you can simply supply a format to the .ToString() method or use one of the DateTime string conversion methods (ie, .ToShortDateString, .ToLongDateString, etc) You can show the date to the user in a more preferable format.
Taking the last example (dt4) you could use
Console.WriteLine(dt4.ToShortDateString) 'and show 4/4/2019
Console.WriteLine(dt4.ToLongDateString) 'and show Thursday, April 4, 2019
Console.WriteLine(dt4.ToString("MM/dd/yyyy")) 'and show 04/04/2019

Compare code date to sql date ASP NET

I get the error about convert type date when i try to compare this :
Page Load :
Dim DataCorrenteLoad As String = DateTime.Now.ToString("dd-MM-yyyy")
Label2.Text = DataCorrenteLoad
and in SqlDataSource the where condition is that the FinishDate >= Today date
How can i solve this situation ? Should i change the format dd-mm-yyyy ? Or what ?
Thanks.
Seems, you want to compare dates, but you kept your focus on string representation of a date. This is not the same!
Take a look at example:
Dim DatabaseDate As DateTime = DateTime.Today.AddDays(-5)
Dim CurrentDate As DateTime = DateTime.Today
'case 1: compare and display date in current culture - depending on regional settings
Console.WriteLine("{0} {1} equal to {2}", DatabaseDate.ToString("d"), If(DatabaseDate=CurrentDate, "is", "is not") , CurrentDate.ToString("d"))
'case 2: change string representation of date:
'compare dates in France and German format
Dim cu1 As Globalization.CultureInfo = New Globalization.CultureInfo("Fr-fr")
Dim cu2 As Globalization.CultureInfo = New Globalization.CultureInfo("De-de")
DatabaseDate = DateTime.Today
Console.WriteLine("{0} {1} equal to {2}", DatabaseDate.ToString("d", cu1), If(DatabaseDate=CurrentDate, "is", "is not") , CurrentDate.ToString("d", cu2))
Above code returns:
'case 1
2017-06-08 is not equal to 2017-06-13
'case 2
13/06/2017 is equal to 13.06.2017
Conclusion:
Depending on OS regional settings, the date format may differ, but the date is still the same!
For further details, i'd strongly recommend to read these:
Standard Date and Time Format Strings
Custom Date and Time Format Strings
Parsing Date and Time Strings in .NET
Design and Implementation Guidelines for Web Clients
Formatting Date and Time for a Specific Culture
Label2.Text= System.DateTime.Now.ToString("dd-mm-yyyy");
use this it will work System.DateTime.Now will show current time when you use To strong("dd-mm-yyyy") it will convert it in to string and set it's formate which u set under double quotes.

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)

Error: Date Type Conversion from String in VB .Net

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)

Sharepoint 2010 dates and calculated fields

For reasons I don't pretend to understand calculated fields that are set to return a date return the value in code in this format:
"datetime;#2015-04-25 00:00:00"
so dim myDate as datetime = oMasterItem("Contract End Date") fails, and you can't cast the value either.
How do I convert that to a real date format without doing string manipulation ?
(or am I missing something obvious?)
Many thanks!
Check this out:
SharePoint - get value of calculated field without manual parsing
You can do it by:
SPFieldCalculated cf = (SPFieldCalculated)myItem.Fields["CIDandTitle"];
string value = cf.GetFieldValueForEdit(myItem["CIDandTitle"]);
or
string value = cf.GetFieldValueAsText(myItem["CIDandTitle"]);