I want to get the date value for
Nov 1, 2010 00:00:00 GMT
expressed in my local time.
What is the best way? Currently, I am doing this:
Dim NovGmt As Date = New Date(2010, 11, 1, 0, 0, 0)
Dim Nov1AsLocal As Date = GetGmtExpressedAsLocal(NovGmt)
Private Function GetGmtExpressedAsLocal(ByVal gmtDate As Date) As Date
Return gmtDate.AddMinutes(GetMinuteOffsetFromGmt)
End Function
Private Function GetMinuteOffsetFromGmt() As Double
Dim NowTime As Date = Now
Dim NowAsGmt As Date = NowTime.ToUniversalTime
Return CType(DateDiff(DateInterval.Minute, NowAsGmt, NowTime), Double)
End Function
Also, can somebody tell me difference between the Date and DateTime datatypes? Is DateTime newer than Date or is it just a synonym for Date? If the latter, why have both?
You can use the ToLocalTime to convert a DateTime from UTC to the local timezone.
Date is an alias for DateTime. I presume this was done for backward compatibility reasons.
Related
I need to calculate time difference between two time
The shift Start time is 04:30:Pm to 12:30AM
The Employee IN time is 08:30 AM then it shows the error message time expired
What I have tried:
dtShifTime = Convert.ToDateTime("16:30").ToString("HH:mm")
Dim dtEntryTime As DateTime = Convert.ToDateTime("08:30").ToString("HH:mm")
If lblStartTime.Text <> "" And (dtLateTime < dtEntryTime) Then
MBox("Time Expired")
End IF
By calling ToString you convert the DateTime object into a String. And then you save it into a DateTime variable.
I don't know what you're trying to do, but to get the difference between two times you just subtract them.
Dim dtStart As DateTime = new DateTime(year:= 1, month := 1, day:= 1, hour:= 8, minute:= 30, second := 0)
Dim dtEnd As DateTime = new DateTime(year:= 1, month := 1, day:= 1, hour:= 20, minute:= 0, second := 0)
Dim tsDiff As TimeSpan = dtEnd - dtStart
Console.WriteLine(tsDiff.ToString())
I recommend you read the documentation for what you're trying to use.
DateTime and TimeSpan.
Instead of the constructor you can parse with DateTime.Parse(), ParseExact or TryParse if you definitely need to use a string as an input, which you should avoid if possible.
Aside from that you should do some basic searching and researching. For example this comes up as the first hit: Get time difference between two timespan in vb.net when searching "time difference vb.net"
Looking to change this Microsoft Word VBA Code so that the expiration date is always every Monday of the week, not a specific date:
Sub MyMacro()
ExpirationDate = #6/1/2013#
If Now() < ExpirationDate Then
'Rest of macro goes here
End if
End Sub
Any thoughts on how to do this would be great :)
If Weekday(Date) = 2 Then ... 'Monday
Public Function FindMonday(dt As Date) As Date
Do Until WeekdayName(Weekday(dt)) = "Monday"
dt = DateAdd("d", 1, dt)
Loop
FindMonday = dt
End Function
ExpirationDate = (Date + 7) - (Weekday(Date) - Weekday(vbMonday))
This formula will always return the date of next Monday, as specified by "+7"
You don't need to declare the variable Expirationdate.
If Date < (Date + 7) - (Weekday(Date) - Weekday(vbMonday)) Then
will do the job.
Note that Now returns a date/time value whereas Date returns a date integer. If time is of the essence you would have to add it in. Add 0.5 to the above formula to fix the expiration time on next Monday, 12 noon.
I'd usually use this function:
Public Function PreviousMonday(CurrentDate As Date) As Date
PreviousMonday = CurrentDate - Weekday(CurrentDate - 2)
End Function
You can then call it as:
PreviousMonday(Date()) - would return 24/07/2017 if entered today (28th).
PreviousMonday(CDATE("1 July 2017")) - would return 26/06/2017
PreviousMonday(42430) would return 29/02/2016 (42430 = 1st March 2016).
I have a vb net project where I have multiple forms each outfitted with a datetimepicker.
For some reason, my datetimepicker in any form isn't returning the selected value i pick but rather, it only returns the current date. I'm ultimately trying to get a string out of the datetimepicker in the format of "YYYYMMDD" (i.e Jan 12, 2016 = "20160112") using a private function below:
for example I picked on my datetimepicker Jan 12, 2016. However the function computes y = 2016, m = 6, and d = 9 as today is Jul 9, 2016.
Private Function getdatefromdatepicker() As String
Dim y, m, d As String
y = Me.DateTimePicker.Value.Year.ToString()
m = Me.DateTimePicker.Value.Month.ToString()
d = Me.DateTimePicker.Value.Day.ToString()
Return y & m & d
End Function
I'm lost with this. If someone could solve how to extract the selected date and get the string format I desire, that would be great. Thanks in Advance.
The DateTimePicker exposes the DateTime value through the Value property. You can then use use Day, Month and Year to get the values like so:
int day = DateTimePicker.Value.Day;
int month = DateTimePicker.Value.Month;
int year = DateTimePicker.Value.Year;
I have a DateTimePicker named dtpDateSelection. When I select a date I need to break the date down into two variables. I need Quarter to equal the quarter that the date is in. And I need Year to equal the year that the date is in. I thought I knew how to do this but I'm having trouble. Here is the code I've tried:
Dim Year As String = DatePart("yyyy", dtpDateSelection)
Dim Quarter As String = DatePart("q", dtpDateSelection)
And this is the error I get:
Additional information: Argument 'DateValue' cannot be converted to type 'Date'.
A simple solution:
Dim year As Integer = DateTimePicker.Value.Year
Dim quarter As Integer = ((DateTimePicker.Value.Month - 1) \ 3) + 1
So you have the DateTime value from the DateTimePicker.Value property.
Using that you can retrieve the year of the date, like this:
Dim year As Integer = DateTimePicker.Value.Year
For determining the quarter the date is within, try this:
Public Shared Function DetermineQuarter(dateTime As DateTime) As Integer
If dateTime.Month <= 3 Then
Return 1
End If
If dateTime.Month <= 6 Then
Return 2
End If
If dateTime.Month <= 9 Then
Return 3
End If
Return 4
End Function
Now you can get the quarter value, like this:
Dim quarter As Integer = DetermineQuarter(DateTimePicker.Value)
As others pointed out, a DateTime value has a .Month member. For the quarter, I have always used a simple Choose function
Dim quarter As Integer = Choose(DateTimePicker1.Value.Month, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4)
Beyond that, your two lines of code work, but you need to add the .Value to the end of dtpDateSelection. The DatePart function 2nd parameter has an Object type, so it will allow you to pass in a control (which is what you are doing), but the end result will be an error. The .Value changes it to the date selected in the picker.
Dim Year As String = DatePart("yyyy", dtpDateSelection.Value)
Dim Quarter As String = DatePart("q", dtpDateSelection.Value)
How do I achieve the same in VB.NET which is so easily done in SQL Server.
SELECT CAST(GETDATE() AS VARBINARY(8)) --GIVES THE CURRENT TIME IN HEX
Now my question is how can I create the same string in VB.NET so that I can compare in SQL Server as such -
SELECT CASE WHEN GETDATE()=CAST(0X00009F5E00D8DF7C AS DATETIME) THEN 'TRUE' ELSE 'FALSE' END -- 0X00009F5E00D8DF7C WILL BE THE VALUE I GET IN VB.NET WHEN I CONVERT IT DATE.NOW() TO HEX
This answer simply addresses conversion of .NET DateTimes to a binary format that is equivalent to SQL Server's datetime datatype, so I believe it is different enough that it warrants a separate answer (I checked here and here to be sure it was ok).
As #Martin Smith pointed out, the binary format of datetime is not simply a number of ticks since a specific point in time.
datetime is stored as 8 bytes, the first 4 bytes being the number of days since 01-01-1900 and the the second 4 bytes being the number of "ticks" since midnight of that day, where a tick is 10/3 milliseconds.
In order to convert a .NET DateTime to an equivalent binary representation, we need to determine the number of days since '01-01-1900', convert that to hex, and then the number of ticks since midnight, which is slightly complicated since a .NET tick is 100ns.
For example:
DateTime dt = DateTime.Now;
DateTime zero = new DateTime(1900, 1, 1);
TimeSpan ts = dt - zero;
TimeSpan ms = ts.Subtract(new TimeSpan(ts.Days, 0, 0, 0));
string hex = "0x" + ts.Days.ToString("X8") + ((int)(ms.TotalMilliseconds/3.33333333)).ToString("X8");
When I ran this code, dt was 9/14/2011 23:19:03.366, and it set hex to 0x00009F5E01804321, which converted to 2011-09-14 23:19:03.363 in SQL Server.
I believe you will always have a problem getting the exact date because of rounding, but if you can use a query where the datetime doesn't have to match exactly, down to the millisecond, this could be close enough.
Edit
In my comment under the first answer I posted, I asked about SQL Server 2008, because the datetime2 data type does store time with an accuracy of 100ns (at least, it does with the default precision), which matches up nicely with .NET. If you are interested in how that is stored at the binary level in SQL Server, see my answer to an older question.
I had to convert some dates in dbscript from SQL Server's hex format string to standard datetime string (for use with TSQL to MySQL script translation). I used some codes I looked up in here and came up with:
static string HexDateTimeToDateTimeString(string dateTimeHexString)
{
string datePartHexString = dateTimeHexString.Substring(0, 8);
int datePartInt = Convert.ToInt32(datePartHexString, 16);
DateTime dateTimeFinal = (new DateTime(1900, 1, 1)).AddDays(datePartInt);
string timePartHexString = dateTimeHexString.Substring(8, 8);
int timePartInt = Convert.ToInt32(timePartHexString, 16);
double timePart = timePartInt * 10 / 3;
dateTimeFinal = dateTimeFinal.AddMilliseconds(timePart);
return dateTimeFinal.ToString();
}
static string HexDateToDateString(string dateHexString)
{
int days = byte.Parse(dateHexString.Substring(0, 2), NumberStyles.HexNumber)
| byte.Parse(dateHexString.Substring(2, 2), NumberStyles.HexNumber) << 8
| byte.Parse(dateHexString.Substring(4, 2), NumberStyles.HexNumber) << 16;
DateTime dateFinal = new DateTime(1, 1, 1).AddDays(days);
return dateFinal.Date.ToString();
}
Maybe not optimized, but shows the idea.
My first inclination is that the clients should not be constructing sql statements to be executed by your data access layer, but assuming you must get something working soon, you might consider using a parameterized query instead.
If you are making method calls from the client(s) to your other application tiers, you can construct a SqlCommand on the client and pass that to the next tier where it would be executed.
VB.NET is not the language I normally use, so please forgive any syntax errors.
On the client:
Dim dateValue As Date = DateTime.Now
Dim queryText As String = "SELECT CASE WHEN GETDATE() = #Date THEN 'True' ELSE 'False' END"
Dim command As SqlCommand = New SqlCommand(queryText)
command.Parameters.AddWithValue("#Date", dateValue)
If you must send a string, you could convert the DateTime to a string on the client and then convert back to a DateTime on the data access tier, using a common format.
On the client:
Dim queryText As String = "SELECT CASE WHEN GETDATE() = #Date THEN 'True' ELSE 'False' END"
Dim dateValue As Date = DateTime.Now
Dim dateString = DateTime.Now.ToString("M/d/yyyy H:mm:ss.fff", DateTimeFormatInfo.InvariantInfo)
Then send both queryText and dateString to the next tier in your application, where it would convert back to Date and again use a parameterized query:
Dim dateValue As Date
Date.TryParseExact(dateString, "M/d/yyyy H:mm:ss.fff", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, dateValue)
Dim command As SqlCommand = New SqlCommand(queryText)
command.Parameters.AddWithValue("#Date", dateValue)
If your clients are in different time zones, you should (as #Martin Smith mentioned) consider using UTC time.
In .NET
Dim dateValue = DateTime.UtcNow
and also in your query, using GETUTCDATE():
Dim queryText As String = "SELECT CASE WHEN GETUTCDATE() = #Date THEN 'True' ELSE 'False' END"