为了给出下面代码的更多信息,PickUpTime是一个字符串,需要像我一样格式化。 GetRandom(int,int)生成一个包含第一个数字的随机数,但不包括第二个数字。它用于提交我无法控制的网络表单。开始的日子基本上是商店营业时间,只能在这几个小时之间选择一个时间。最后的字符串只能是" 8:00 AM"或者" 8:30 AM"。
Saturday 9am-3pm
Sunday 11am-5pm
Weekdays 8am-6pm
我只是在寻找一种更有效的编写代码的方法。我一直在盯着它认为必须有办法,但我无法弄明白。任何帮助表示赞赏。代码确实在当前状态下工作。我只是想学习更好的编码实践。
If Date1.DayOfWeek = DayOfWeek.Saturday Then
i = GetRandom(2, 15)
ElseIf Date1.DayOfWeek = DayOfWeek.Sunday Then
i = GetRandom(6, 19)
Else
i = GetRandom(0, 21)
End If
If i=0 Then
PickUpTime = "8:00 AM"
ElseIf i=1 Then
PickUpTime = "8:30 AM"
ElseIf i=2 Then
PickUpTime = "9:00 AM"
ElseIf i=3 Then
PickUpTime = "9:30 AM"
ElseIf i=4 Then
PickUpTime = "10:00 AM"
ElseIf i=5 Then
PickUpTime = "10:30 AM"
ElseIf i=6 Then
PickUpTime = "11:00 AM"
ElseIf i=7 Then
PickUpTime = "11:30 AM"
ElseIf i=8 Then
PickUpTime = "12:00 AM"
ElseIf i=9 Then
PickUpTime = "12:30 PM"
ElseIf i=10 Then
PickUpTime = "1:00 PM"
ElseIf i=11 Then
PickUpTime = "1:30 PM"
ElseIf i=12 Then
PickUpTime = "2:00 PM"
ElseIf i=13 Then
PickUpTime = "2:30 PM"
ElseIf i=14 Then
PickUpTime = "3:00 PM"
ElseIf i=15 Then
PickUpTime = "3:30 PM"
ElseIf i=16 Then
PickUpTime = "4:00 PM"
ElseIf i=17 Then
PickUpTime = "4:30 PM"
ElseIf i=18 Then
PickUpTime = "5:00 PM"
ElseIf i=19 Then
PickUpTime = "5:30 PM"
ElseIf i=20 Then
PickUpTime = "6:00 PM"
End If
WebBrowser1.Document.GetElementById("Time").SetAttribute("value", PickUpTime)
答案 0 :(得分:1)
完成我的回答 - 尽管如此,achan回答最具可读性并且有意义:
Dim formattedTime As String
' Setting meridiem
If i < 8 Then
formattedTime = "AM"
Else
formattedTime = "PM"
End If
' Setting minutes
If i Mod 2 = 0 Then
formattedTime = ":00 " & formattedTime
Else
formattedTime = ":30 " & formattedTime
End If
' Setting hours
If i <= 9 Then
formattedTime = (i + 16) \ 2 & formattedTime
Else
formattedTime = (i - 8) \ 2 & formattedTime
End If
答案 1 :(得分:1)
您可以替换巨人如果以If i = 0 ....开头,则使用以下内容:
PickupTime = New DateTime(2000, 1, 1, (i+16) \ 2, 30 * (i Mod 2), 0).TimeOfDay.ToString()
答案 2 :(得分:1)
Dim dt As DateTime = New DateTime(2015, 9, 1, 8, 0, 0)
dt = dt.AddHours(i * 0.5)
Dim PickupTime As String = dt.ToString("h:mm tt")
希望......这种方法更易于阅读和维护
答案 3 :(得分:0)
定义一个String数组,然后根据随机函数生成的索引获取值。
Dim array(n) As String
array(0) = "8:00 am"
.....
array(n) = "6:00 pm"
If Date1.DayOfWeek = DayOfWeek.Saturday Then
i = GetRandom(2, 15)
ElseIf Date1.DayOfWeek = DayOfWeek.Sunday Then
i = GetRandom(6, 19)
Else
i = GetRandom(0, 21)
End If
formattedTime = array(i)