Question

I'm making a alarm clock in my application and the code requires me to set a variable int from a combo box into my program.

if ((e.Result.Text == "set a alarm") || (e.Result.Text == "set an alarm"))
        {
            Jarvis.Speak("setting alarm");
            label2.Content = DateTime.Today.Hour.ToString(HourAlarmCB) + ":" + DateTime.Today.Minute.ToString("54") + ":" + DateTime.Today.Second.ToString("00");
            label2.Opacity = 100;
            dispatcherTimer2.Start();
        }

The HourAlarmCB is the ComboBox with content in it "1","2", etc. but the error wont allow me to use ToString, is there any way around this?

Was it helpful?

Solution

I believe that you may be incorrectly making use of ToString().

Are you trying to retrieve the following formatted result?

hh:mm:ss

If so, you might find this approach worthy of consideration:

int hour = Convert.ToInt32(HourAlarmCB.SelectedItem);
int minute = DateTime.Today.Minute;
int second = DateTime.Today.Second;
label2.Content = String.Format("{0:D2}:{1:D2}:{2:D2}", hour, minute, second);

See String.Format for converting an arbitrary list of variables into a single formatted string.

For a description of "D2", see Standard Numeric Format Strings.


Update: First, note that DateTime.Today returns "an object that is set to today's date, with the time component set to 00:00:00."

Now, in reference to your question, to output AM or PM, use the t standard format string:

DateTime date = DateTime.Today; // time is '00:00:00'
int hour = Convert.ToInt32(HourAlarmCB.SelectedItem);
int minute = date.Minute; // always '0'
int second = date.Second; // always '0'

label2.Content = String.Format("{0:D2}:{1:D2}:{2:D2} {3:t}",
    hour, minute, second, date); // for example: '08:00:00 AM'

OTHER TIPS

So the end result is me having to the HourAlarmCB variable to a string

if ((e.Result.Text == "set a alarm") || (e.Result.Text == "set an alarm"))
        {
            Jarvis.Speak("setting alarm");
            string HourAlarmStr = HourAlarmCB.SelectedItem.ToString();
            label2.Content = DateTime.Today.Hour.ToString(HourAlarmStr) + ":" + DateTime.Today.Minute.ToString("54") + ":" + DateTime.Today.Second.ToString("00");
            label2.Opacity = 100;
            dispatcherTimer2.Start();
        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top