Reputation: 1021
I have programmed a form in Visual Basic which displays the current system time (hh:mm:ss) in a label called "DigitalTime".
Now for the hard part: How do I program a second label ("WordTime") to use the current time (from "DigitalTime") and show it in the "WordTime" label in words like this:
Example 1: (time is 22:50) I want label "WordTime" to show "10 minutes to 11".
Example 2: (time is 13:15) I want label "WordTime" to show "15 minutes past 1".
For the minutes 0-30 I want it to display "... minutes past ...". For the minutes 31-59 I want it to display "... minutes to ...".
Upvotes: 0
Views: 95
Reputation: 179
It turns out that it isn't that hard thanks to the wonderful ToString formatters available for DateTime in .NET and using String.Format. The DateTime structure in general has all you need to know on this stuff. One caveat and a gotcha, to subtract time from a current DateTime we Add negative amounts of time. There is no SubtractMinutes
method on DateTime, only AddMinutes
, so you add negative time.
With all that said something like this below. Ideally you'd just make it a function, but I left it fairly basic so it wouldn't get confusing.
10 minutes to 11:
Dim _textToMinute As String = String.Empty
If DateTime.Now().Minute > 30 Then
_TextToMinute = "Past"
Else
_textToMinute = "To"
End If
Dim _minutesTillNextHour = (DateTime.Now().AddHours(1).AddMinutes(-DateTime.Now().Minute) - dateTime.Now).Minutes
Dim _nextHour = DateTime.Now().AddHours(1).ToString("%h")
label1.Text = String.Format("{0} minutes {1} {2}", _minutesTillNextHour, _textToMinute, _nextHour)
15 minutes past 1
label1.Text = String.Format("{0} minutes {1} {2}", DateTime.Now().Minute, _textToMinute, DateTime.Now().ToString("%h"))
Upvotes: 1
Reputation: 6948
When the minutes is 30,it is common practice to use the word "half", as in "half past 6". Here's a simple little function that takes that into account and returns a formatted string that can be assigned wherever you need it:
Function TimeInCommonLang(ByVal input As DateTime) As String
Dim minutes As String = ""
Dim indicator As String = ""
If input.Minute <= 30 Then
indicator = "past"
If input.Minute = 30 Then
minutes = "half"
Else
minutes = input.Minute.ToString & " minutes"
End If
Else
indicator = "to"
minutes = (60 - input.Minute).ToString & " minutes"
input = input.AddHours(1)
End If
Return String.Format("{0} {1} {2}", minutes, indicator, input.ToString("%h"))
End Function
Upvotes: 0