Search code examples
c#timespansecondsminute

TimeSpan Conversion


I want to convert minutes to seconds and at the moment I have a problem because in the minute textbox when I type 1.50 the outcome is 90 seconds which is wrong because 1.30 = 90 seconds

    private void MtoCbutton_Click(object sender, EventArgs e)
    {
        if (minTosecTextBox.Text != "Minutes")
        {
            minutes = Convert.ToDouble(minTosecTextBox.Text);
            TimeSpan span = TimeSpan.FromMinutes(minutes);
            resultSectextBoxtextBox.Text = span.TotalSeconds.ToString();
        }

        else
        {

            MessageBox.Show("Please enter Minutes");
        }

Solution

  • To convert from seconds to minutes you simply need to divide by 60.0 (you need the decimal or it will be treated like an integer). If treated like an integer and you pass 30 seconds, 30/60 will equal 0.

    Also use double.TryParse method. Right now if someone enters 1.50xx, your application will crash. Either use double.TryParse method or use a try catch mechanism or only allow numeric entry.

    EDIT

    This will accomplish what you want. I added a label to show the output but you can remove it.

    double enteredNumber;
    if (double.TryParse(minTosecTextBox.Text, out enteredNumber))
    {
        // This line will get everything but the decimal so if entered 1.45, it will get 1
        double minutes = Math.Floor(enteredNumber);
    
        // This line will get the seconds portion from the entered number.
        // If the number is 1.45, it will get .45 then multiply it by 100 to get 45 secs
        var seconds = 100 * (enteredNumber - Math.Floor(enteredNumber));
    
        // now we multiply minutes by 60 and add the seconds
        var secondsTotal = (minutes * 60 + seconds);
    
        this.labelSeconds.Text = secondsTotal.ToString();
    }
    
    else
    {
    
        MessageBox.Show("Please enter Minutes");
    }
    

    EDIT 2

    Some further clarification

    You are not converting minutes to seconds since if you were then 1.5 (1 minute and a half) would equal 90 seconds. This is logical and obvious. You are treating only the part before the decimal as minutes and the part after the decimal is to be treated as seconds (1.30 = 1 minute and 30 seconds = 90 seconds). Therefore we only need to convert the part before the decimal to seconds and add to it the part after the decimal.