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.. ;)
Related
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.
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)
I'm using a timespan function to work out the number of days, this value is then added to a text box and saved to the database.
I have recently added a radio button as a half day so it if is checked it adds 0.5 days holiday rather than 1 day. This seems to work correctly when displayed in the text box before being saved. However, when it actually saves and updates the database shows a value of 1 rather than 0.5 as shown in text box.
The fieldtype in the database for this field was originally set to 'int'but when I added the half day it would not save as it was trying to save a decimal figure, I have since changed this fieldtype to 'decimal' as it thought this would be more suitable.. i'm not sure if this is correct or it should be something different?
I cannot seem to figure out why it is not saving the value specified in the text box...any suggestions
Private Sub btnHNoDays_Click(sender As Object, e As System.EventArgs) Handles btnHNoDays.Click
'declare dates
Dim dtStart As Date = txtHStart_Date.Text
Dim dtEnd As Date = txtHEnd_Date.Text
'timespan function used to minus one date to another and produce a value
Dim ts As TimeSpan = (dtEnd - dtStart)
If RadioButton1.Checked Then
ts = (dtEnd - dtStart) - TimeSpan.FromDays(0.5)
Else
ts = (dtEnd - dtStart)
End If
' the value is set to to textbox.
txtNoofDays.Text = ts.TotalDays()
' the today days value
Console.WriteLine(ts.TotalDays)
End Sub
Protected Sub btnHRequestSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnHRequestSave.Click
'collect data
Dim Sdate = txtHStart_Date.Text
Dim Edate = txtHEnd_Date.Text
Dim NoofDays = txtNoofDays.Text
Dim notes = TxtHRequestNotes.Text
Dim username = lblHolidayRequestLIU.Text
'define connection
Dim HRequestConnection As New SqlConnection
HRequestConnection.ConnectionString = HolidayRequestSqlDataSource.ConnectionString
'create command
Dim HRequestInsert As New SqlCommand("Insert into HolidayRequests (username, RequestDateStart, RequestDateEnd, RequestTotalDays, RequestNotes) VALUES (#username, #Sdate, #Edate, #NoofDays, #notes)", HRequestConnection)
'define parameters
HRequestInsert.Parameters.Add("username", SqlDbType.NVarChar, 20).Value = lblHolidayRequestLIU.Text
HRequestInsert.Parameters.Add("Sdate", SqlDbType.Date).Value = txtHStart_Date.Text
HRequestInsert.Parameters.Add("Edate", SqlDbType.Date).Value = txtHEnd_Date.Text
HRequestInsert.Parameters.Add("NoofDays", SqlDbType.Decimal).Value = txtNoofDays.Text
HRequestInsert.Parameters.Add("notes", SqlDbType.NVarChar).Value = TxtHRequestNotes.Text
' execute commands
HRequestConnection.Open()
HRequestInsert.ExecuteNonQuery()
lblHolRequestResponse.Text = "Your holidays request has been saved!
End Sub
How have you specified the decimal column in the database? Have you given it precision and scale (see here)? If not, it defaults to decimal(18,0) which will give you no figures after the decimal point.
You should give it a type along the lines of decimal(5,1) depending on your requirements.
Bear in mind that precision is the number of total digits (to the left and right of the decimal point) and scale is the number to the right of the decimal point. Therefore decimal(5,1) could store up to 9999.9.
(I'm assuming you're using SQL Server)