Search code examples
c#windows-phone-7.1windows-phone-7.1.1

How to calculate a price based on time passed in c#?


I'm currently working on an app that calculates the price a user has to pay for a service based on how much time he's spent using said service. The fee is $3.30 for the first hour and then $1.15 for every half hour after that. My timer looks something like this:

    private void timer()
    {
        DispatcherTimer timer = new DispatcherTimer();

        timer.Tick +=
            delegate(object s, EventArgs args)
            {
                TimeSpan time = (DateTime.Now - StartTime);

                this.Time.Text = string.Format("{0:D2}:{1:D2}:{2:D2}", time.Hours, time.Minutes, time.Seconds);
            };
        timer.Interval = new TimeSpan(0, 0, 1); // one second
        timer.Start();
    }

The point being that the timer AND the price to pay should be shown on screen and update automatically with the passing of time (the timer already does that.)

As for the price itself, I thought of using a combination of if/else and foreach, but so far, I've accomplished nothing...


Solution

  • If the scheme is such that the cost is added as soon as a segment starts then you can calculate the number of half hours that have started, after the initial hour, as:

    Math.Round((hours - 1) / 0.5 + 0.5)
    

    And the cost is then calculated as:

    double hours = (DateTime.UtcNow - StartTime).TotalHours;
    double cost;
    if (hours < 1)
        cost = 3.30;
    else
        cost = 3.30 + Math.Round((hours - 1) / 0.5 + 0.5) * 1.15;