I am trying to determine the correct method of adding the current amount of Daylight Savings Time to a ZonedDateTime. The following method seems to be OK, as long as the amount is a positive amount, but I wonder if there is a better method?
' Get the current moment in time
Dim now As Instant = SystemClock.Instance.GetCurrentInstant()
' Convert to UTC time
Dim UtcDateTime As ZonedDateTime = now.InUtc
' Get this computer's Local TimeZone
Dim LocalTimeZone As DateTimeZone = DateTimeZoneProviders.Tzdb.GetSystemDefault()
' Convert the UTC DateTime to the time in the Local TimeZone
Dim LocalDateTime As ZonedDateTime = UtcDateTime.WithZone(LocalTimeZone)
' The above code is just to set things up. The following code is the question:
' Check if Daylight Savings Time is in force
Dim DstInForce As Boolean = LocalDateTime.IsDaylightSavingTime
' Get the Interval for the Local TimeZone
Dim LocalInterval As ZoneInterval = LocalTimeZone.GetZoneInterval(LocalDateTime.ToInstant)
' If Daylight Savings Time is in force, add the Savings Amount
If DstInForce = True Then
LocalDateTime.PlusSeconds(CLng(LocalInterval.Savings.ToTimeSpan.TotalSeconds))
End If
EDITED ADDITION..
Here is another working example:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim NowDateTime As LocalDateTime = New LocalDateTime(2020, 8, 5, 9, 15)
Dim UtcZone As DateTimeZone = DateTimeZoneProviders.Tzdb("UTC")
Dim UtcDateTime As ZonedDateTime = NowDateTime.InZoneLeniently(UtcZone)
TextBox1.AppendText("It is currently " & UtcDateTime.ToString & " in zone " & UtcZone.ToString & vbCrLf)
Dim ThisComputerTimeZone As DateTimeZone = DateTimeZoneProviders.Tzdb("Europe/London")
Dim ThisComputerDateTime As ZonedDateTime = UtcDateTime.WithZone(ThisComputerTimeZone)
' Check if Daylight Savings Time is in force
Dim DstInForce As Boolean = ThisComputerDateTime.IsDaylightSavingTime
Dim ThisComputerInterval As ZoneInterval = ThisComputerTimeZone.GetZoneInterval(ThisComputerDateTime.ToInstant)
If DstInForce = True Then
' If Daylight Savings Time is in force, add the Savings Amount
ThisComputerDateTime.PlusSeconds(CLng(ThisComputerInterval.Savings.ToTimeSpan.TotalSeconds))
End If
TextBox1.AppendText("It is currently " & ThisComputerDateTime.ToString & " in local zone " & ThisComputerTimeZone.ToString & vbCrLf)
TextBox1.AppendText("Daylight Savings Time is '" & DstInForce & "' and has been applied." & vbCrLf)
End Sub
Here is its output:
It is currently 2020-08-05T09:15:00 UTC (+00) in zone UTC
It is currently 2020-08-05T10:15:00 Europe/London (+01) in local zone Europe/London
Daylight Savings Time is 'True' and has been applied.
As you can see, I needed to add the extra Savings amount to change the UTC time '09:15' to the Daylight Savings time '10:15'. What am I trying to do? I am trying to create a UTC time, then change it to the local time of my computer, with the correct DST amount included. These steps are part of a larger process, abbreviated for clarity.
You don't need any of the code after "Check if Daylight Savings Time is in force" - it's already taken into account by the WithZone method. Your code isn't actually doing anything useful anyway because you're ignoring the result of PlusSeconds - that doesn't modify the existing ZonedDateTime, it returns a new one.
This line:
Dim ThisComputerDateTime As ZonedDateTime = UtcDateTime.WithZone(ThisComputerTimeZone)
... does all that you need it to. WithZone takes daylight saving time into account already. There's no need to try to manually adjust it.
Related
Is there a way to programmatically find the Date/Time format of a string in Visual Basic?
My example comes from work. I was working on an Custom Web Page to compare tables on Excel Spreadsheets . My comparison of the records on each table is based off of last four digits of social security and birthdate, however currently the format of the birthdate has to be the same on both spreadsheets for it to run properly. The user wanted to compare early before we had updated the reports for this project, and I told her to make sure the birthday columns were in the same datetime format before she ran the web page. She did not.
I have two options, hard code the date time format that currently exists on the spreadsheets, or find a way to make the format irrelevant. I think it would be more fun to do the latter.
I know that there is a Date.ParseExact method, but that requires that you know the format of the string already.
To give you a better idea of what I want to do:
Dim Birthday1 As String = "04/15/1998 13:00:00"
Dim Birthday2 As String = "04/15/1998 1:00 PM"
'//Converts to Date in format "M/d/yyyy"
Dim dateBirthday1 As Date = ConvertFromAnyDateFormat(Birthday1)
Dim dateBirthday2 As Date = ConvertFromAnyDateFormat(Birthday2)
If dateBirthday1 = dateBirthday2 Then
'//Do comparison operations or whatever
End If
In your case, the strings are in good format. So just allow the system to cast the values
This will work for your two dates.
Imports System.Globalization
Public Class MyFunExample
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Birthday1 As String = "04/15/1998 13:00:00"
Dim Birthday2 As String = "04/15/1998 1:00 PM"
Dim Birthday3 As String = "04/15/98 1:00 PM"
Dim Birthday4 As String = "04/15/98"
'//Converts to Date in format "M/d/yyyy"
Dim dtBir1 As DateTime = Birthday1
Dim dtBir2 As DateTime = Birthday2
Dim dtBir3 As DateTime = MyDateCheck(Birthday3)
Dim dtBir4 As DateTime = MyDateCheck(Birthday4)
Debug.Print(dtBir1)
Debug.Print(dtBir2)
Debug.Print(dtBir3)
Debug.Print(dtBir4)
if dtBir1 = dtBir2 then
End if
End Sub
Function MyDateCheck(sDate As String) As DateTime
If IsDate(sDate) Then
Return sDate
End If
Dim rFoundOne As DateTime
' if we get here, then lets try some other formats
If DateTime.TryParse(sDate, CultureInfo.InvariantCulture, DateTimeStyles.AllowInnerWhite, rFoundOne) Then
Return rFoundOne
End If
' try additonal messy cases
If DateTime.TryParseExact(sDate, "mm dd yy", CultureInfo.InvariantCulture, DateTimeStyles.AllowInnerWhite, rFoundOne) Then
Return rFoundOne
End If
' if all fail, then we return a "0" date
Return DateTime.MinValue
End Function
Output:
1998-04-15 1:00:00 PM
1998-04-15 1:00:00 PM
1998-04-15 1:00:00 PM
1998-04-15
So if things are messed up - then you could introduce the date check routine, but in your case you just need to shove the strings into a datetime, and thus they are then considered NOT a string, but a internal date format number, and thus the compares will work.
So, got myself into this thing that I thought would be a walk in the park, until I discovered how difficult it is working with things that needs to be calculated between hours that passes midnight.
In short, Im writing an app for work in which my vision is to visualize the production for the operators during their shift. Doing so, I need to declare shift times (which I got excellent help with in previous question), but I also need to calculate how many hours passed since the current shift started. This is in order to calculate efficiency (based on maxproducts (hourspassed * maxcapacity/h) / productsmade *100). Calculating the timespan works flawlessly, until nightshift starts. Their hours is 23:00-06:00 and I just cant get the accurate hours for when it overlaps midnight.
Current code used for calculating this is:
Dim startTime As DateTime = Label46.Text ' Shift start Time
Dim endTime As DateTime = DateTime.Now.ToString("HH:mm:ss") ' Current time
Dim span As TimeSpan = endTime.Subtract(startTime)
Dim span2 As Double = (span.Hours)
Label35.Text = span2 ' displays hours passed since shiftstart
I'm fresh at coding more or less, I'm still in a stage where I try my best to learn and understand every function instead of just using copy paste.
This has got my head in though, not even google seems to be willing to help me.
Thankful for ANY asisstance, or hints on this issue.
Im thinking an easy way of getting through it, such as using 00:00-06:00 as workinghours and then just do + 1 to passed hours during that timespan but seems cheesy..
This works:
If DateTime.Now > DateTime.Now.ToShortDateString & " 00:00:01" And DateTime.Now < DateTime.Now.ToShortDateString & " 05:59:59" Then
Dim startTimeN As DateTime = "00:00:01" ' Shift start Time
Dim endTimeN As DateTime = DateTime.Now.ToString("HH:mm:ss") ' Current time
Dim span1 As TimeSpan = endTimeN.Subtract(startTimeN)
Dim span3 As Double = (span1.Hours)
Label35.Text = span3 + 1
Else
Dim startTime As DateTime = Label6.Text.ToString() ' Shift start Time
Dim endTime As DateTime = DateTime.Now.ToString("HH:mm:ss") ' Current time
Dim span As TimeSpan = endTime.Subtract(startTime)
Dim span2 As Double = (span.Hours)
Label35.Text = span2
End If
But this feels like cheating.. ;)
how to convert a time value which display a duration, to another time value to another time zone please
I'm doing an auction website, i display the duration of each time, and how to ensure that if someone is in another country, it can show the duration, in his own time zone duration please
Protected Sub Timer1_Tick(ByVal sender As Object, ByVal e As EventArgs)
'--this method will fetch the end date from repeater item label and update the duration
UpdateDuration()
End Sub
Private Sub UpdateDuration()
For Each item As DataListItem In DataList1.Items
'--calculate the duration
Dim duration As TimeSpan = Convert.ToDateTime(TryCast(item.FindControl("lblEndDate"), Label).Text) - DateTime.Now
Dim label2 = TryCast(item.FindControl("lblDuration"), Label)
'--Here is the important part: if any duration is expired then bind the grid again
If (duration.Ticks < 0) Then
'Grab your DateTime object (checking that it exists)'
'Now you can output your time as you please (excluding any decimal points)'
BindItems()
Exit For
Else
'-- showing end date as last days has not arrived
TryCast(item.FindControl("lblDuration"), Label).Text = New DateTime(duration.Ticks).ToString("dd:HH:mm:ss")
label2.Text = String.Format("{0:dd\:hh\:mm\:ss}", duration)
label2.Text = Replace(label2.Text, ":", " Days ", , 1)
label2.Text = Replace(label2.Text, ":", " Hours ", , 1)
label2.Text = Replace(label2.Text, ":", " Mins ", , 1)
End If
Next
End Sub
This following line in javascript can give you the timezoneoffset of client machines time zone with respect to UTC (For further information visit this link):
var offset = new Date().getTimezoneOffset();
Once you know the offset you can make use of the following C# code to get the UTC time:
DateTime UtcNow = DateTime.UtcNow;
You can save the offset in a hidden field at client and once on server store it in a session for each user. Based on the sign of the offset you will need to decide whether to add or subtract minutes from UTC time. If the value is negative say -330 then add 330 mins to UTC datetime, and if value is positive say 20 then subtract 20 mins from UTC datetime. e.g.
DateTime clientTime=UtcNow.AddMinutes(20)
The above instructions will help you achieve what you desire. But I would also like to give you a piece of advise concerning security. No decision should be taken based on the data that you derive from the client as this data may have been tempered. Timezone offset that you fetch from the client should only be used to display time on their browser, but it should not affect the fact that your auction would run say 1hr from 11 AM CST. Hope you understand the risk here.
Hope this helps. Please ask for clarification if required, specially if you are not clear about what could be the risk.
I push a button on a web page.
I am trying to get the current date into 3 variables Year, Month, and Day
In the Code behind I Have:
Dim intDay As Integer
intDay = Date.Now.Day
I get error message
Input string was not in a correct format.
Suggestions?
There is nothing wrong with the code you posted.
See this ideone for the same code which compiles and executes just fine.
Dim intDay As Integer
intDay = Date.Now.Day
Console.WriteLine(intDay)
The Now property returns the current time as a DateTime value.
On which you can call the Day property which returns an integer
The error message you got refers to a string which is not in the posted code so I'm guessing the problem is somewhere else
As Iam Asp.Net Developer I have Code Like This....
I Take Three Textboxes For Showing YYYY,MM,DD
TextBox1.Text = DateTime.Now.ToString("yyyy");
TextBox2.Text = DateTime.Now.ToString("MM");
TextBox3.Text = DateTime.Now.ToString("dd");
This Gives Output Like This...
2013
08
08
Shouldn't it be:
intDay = DateTime.Now.Day
Edit: didn't see the comment stating the in VB.NET Date is valid too ;)
This is taken straight from the docs. So you should be able to assign DateTime.Now to moment and get what you want from it.
http://msdn.microsoft.com/en-us/library/system.datetime.day.aspx
Dim moment As New System.DateTime(1999, 1, 13, 3, 57, 32, 11)
' Year gets 1999.
Dim year As Integer = moment.Year
' Month gets 1 (January).
Dim month As Integer = moment.Month
' Day gets 13.
Dim day As Integer = moment.Day
' Hour gets 3.
Dim hour As Integer = moment.Hour
' Minute gets 57.
Dim minute As Integer = moment.Minute
' Second gets 32.
Dim second As Integer = moment.Second
' Millisecond gets 11.
Dim millisecond As Integer = moment.Millisecond
I think you want DateTime.Now.Day
Using vb.net am trying to convert utc time to local time .but i think am getting the wrong result. Here i enclosed mycode.
code
Dim time As DateTime = New DateTime()
time = Date.FromFileTimeUtc(1344502618)
MsgBox(time)
getting result like this
1/1/1601 12:02:14 AM
is this result is correct?
You can just write
Dim time As Double = Convert.ToDouble(1344502618)
Dim baseDate As New Date()
Dim result As Date = baseDate.Add(TimeSpan.FromSeconds(time))
MsgBox(result)