Search code examples
c#unity-game-enginetimerformatting

Add timers in the format 00:00?


I have created two timers and they run in the format of 00:00 (Mins:Secs). I would like to add these two timers together and the resulting final timer should also be in the format of 00:00. How do I create the final timer in this way?

eg. Timer 1 = 02:00,
    Timer 2 = 03:30,
    Final Timer = 05:30
    public float Time_1;
    public string Time_1_format = "00:00";

    public float Time_2;
    public string Time_2_format = "00:00";


    string a_1_minutes;
    string a_1_seconds;

    string a_2_minutes;
    string a_2_seconds;

    string final_Time;
    public string Time_3_format = "00:00";



    void Update()
    {
            Time_1 += Time.deltaTime;
            a_1_minutes = Mathf.Floor(Time_1 / 60).ToString("00");
            a_1_seconds = (Time_1 % 60).ToString("00");

            Time_1_format = string.Format("{0}:{1}", a_1_minutes, a_1_seconds);

            Time_2 += Time.deltaTime;
            a_2_minutes = Mathf.Floor(Time_2 / 60).ToString("00");
            a_2_seconds = (Time_2 % 60).ToString("00");

            Time_2_format = string.Format("{0}:{1}", a_2_minutes, a_2_seconds);
    }

Solution

  • All you need to do it Time_Sum = Time_1 + Time_2;

    You can do is because Time_1 and Time_2 are floats.

                public float Time_Sum;
                public string Time_Sum_format = "00:00";
    
                string sum_minutes;
                string sum_seconds;
    
                Time_Sum = Time_1 + Time_2;
                sum_minutes = Mathf.Floor(Time_Sum / 60).ToString("00");
                sum_seconds = (Time_Sum % 60).ToString("00");
    
                Time_Sum_format = string.Format("{0}:{1}", sum_minutes, sum_seconds);