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.
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.
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.. ;)
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
I struggled to come up with appropriate title for this thread.
Forgive me it isn't clearcut.
We have a table called Locations with following attributes:
locationID --Each location has 30 capacity seating per class
Capacity_Seating --this is total allowed seat per class per location.
When a user logs in, s/h is presented with a dropdownlist of locations to choose from. Whichever location the trainee chooses, is the location s/he is going to take the training at.
The Capacity seating for each location is 30.
As soon as the user logs in, s/he is taken to the Trainring page. The training displays general information about the classes, including the date and time of training, duration, the Capacity Seating and most importantly, available seats or Seats remaining.
If seats are still available, the user can click Register to register for that particular training.
Once this user is registered, the available seat changes.
For instance, if there were 15 seats prior to this trainee registering, then after registering, the available seating with now read 14 seats.
If a user chooses to cancel his or her seat after initially registering, the trainee can do so as long as it isn't within 24 hours of training date.
Here are my questions.
1, do I need to add another field called Available_Seats to the location table or to the Training table to show how many seats remain or can this be done using a query like:
Select (Capacity_Seating - each time trainee registers)?? Not sure how to handle this.
2, We would like to use register to substract a number from Capacity_Seating and Cancel to put back a number to Capacity_Seating.
Your thoughts and assistance are greatly appreciated.
<ItemTemplate>
<asp:LinkButton ID="Btncalc" runat="server" Text="Register" tooltip="Click to calculate" onclick="calc" />
</ItemTemplate>
</asp:TemplateField>
</ItemTemplate>
Sub calc(ByVal sender As Object, ByVal e As System.EventArgs)
Dim objConnection As SqlConnection
Dim username = Session.Item("Username").ToString
' Dim strSQL As String
objConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("DBConnectionString").ConnectionString)
objConnection.Open()
strSQL = "update TrainingTable set employeeId='" & username
strSQL += "', AvailableSeats= AvailableSeats-1"
strSQL += " where location = '" & ddlLocation.SelectedValue.ToString & "'"
'Response.Write(strSQL)
'Response.End()
Dim cmdcommand As New SqlCommand(strSQL, objConnection)
cmdcommand.ExecuteNonQuery()
cmdcommand = Nothing
objConnection.Close()
objConnection = Nothing
End Sub
By the way, markup is on gridview.
For your first question how you would like to proceed mostly comes down to what you would like to do. Having another field for the available seats in a table or finding the remaining seats using a query are both viable options. The benefits or pitfalls of either are really negligible given the basic structure of your system. Seeing as you would use a specific query to find this piece of information constantly it would be better practice and sense to add this value in as a new field in the table. This will eliminate the need for a specific query and make this data more public to other systems and queries.
For your second question I'm not quite sure I follow it but I'll try to give you my best opinion. It seems you want to alter the total capacity field from each table based on registrations and cancellations which I would disagree with. The capacity value shouldn't be modified if the actually total capacity of location does not change. So rather than changing the total capacity through cancels or registrations I would change that new available seats field. This leaves no chance for confusion when viewing the capacity of the location and will easily allow you to find the available spaces for registration.
This is a simple module:
It gives you a choice of a particular course, with two venues and an option of reg or adv course at each venue (this doesn't affect the seating)
I have NOT included the SQL OR server side scripts, at this stage.. this algorithm should help.
You don't need to add another column to your table, just update the fields as the program is implemented, and you can delete a row, if it is cancelled. I haven't included code for that.. (it's too long!!! hahaha)
(NB this doesn't error check for datatype - it's a simple format to get an idea)
Module Module1
Sub main()
Dim Seat As Object
Dim Course As Object
Dim Person1 As Integer
Dim Venue1 As Integer
Dim Venue2 As Integer
Dim regular As Integer
Dim Advanced As Integer
Dim x As String
Do
Person1 = Person1 + 1
If Venue1 = 30 Then
Console.WriteLine("Venue1 is full")
End If
If Venue2 = 30 Then
Console.WriteLine("Venue2 is full")
End If
Console.WriteLine("enter 1 for Venue1, 2 for Venue2")
Seat = Console.ReadLine
If Seat = 1 Then
Venue1 = Venue1 + 1
Else
Venue2 = Venue2 + 1
End If
Console.WriteLine("Regular course = 1, Advanced course = 2")
Course = Console.ReadLine
If Course = 1 Then
regular = regular + 1
Else
Advanced = Advanced + 1
End If
Console.WriteLine("Press enter to continue, r for reports or x to quit")
x = Console.ReadLine
If x = "r" Then
Console.WriteLine("total Persons= " & Person1 & vbCrLf & "total Venue1= " & Venue1 & vbCrLf & "total Venue2=" & Venue2 & vbCrLf & "Course: regular " & regular & vbCrLf & "Advanced " & Advanced)
ElseIf x = "x" Then
Exit Do
Else
End If
Loop Until Person1 = 60
If Person1 = 60 Then
Console.WriteLine("Course is full.")
End If
End Sub
End Module
Please let me know if you need any more help or clarity.
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)