How to make 5 minute countdown using TimeOfDay - c#

Candlesticks on stock market charts are created every minute. I have created a count down timer to tell me how many seconds are left until next candlestick is to be created.
//logic for 1 min candlestick
const int MINUTE = 60;
int currentSecond = DateTime.UtcNow.Second;
int nextMin = MINUTE - currentSecond;
minuteLabel.Text = nextMin.ToString();
The chart can also display candlesticks every 5 minutes for a different perspective. So in this scenario a candlestick is created every 5 minutes. This is what I'm having trouble with. How do I create a count down timer to show me how much time is left until the next candlestick is to be created? This is what I have so far:
//inefficient logic for 5 min candlestick
int currentMinute = DateTime.UtcNow.Minute;
int nextFiveMin;
if (currentMinute >= 0 && currentMinute < 5) {
nextFiveMin = ((5 * MINUTE) - (currentMinute * MINUTE)) - currentSecond;
}
else if(currentMinute >= 5 && currentMinute < 10) {
nextFiveMin = ((10 * MINUTE) - (currentMinute * MINUTE)) - currentSecond;
}
else if (currentMinute >= 10 && currentMinute < 15) {
nextFiveMin = ((15 * MINUTE) - (currentMinute * MINUTE)) - currentSecond;
}
//etc all the way to currentMinute > 55
TimeSpan t = TimeSpan.FromSeconds(nextFiveMin);
fiverLabel.Text = t.ToString(#"mm\:ss");
Although this code works fine I think that there's probably a much easier way to implement this that I can't think of.

You can just do this:
int currentMinute = DateTime.UtcNow.Minute;
int diffMinutes = (currentMinute/5 +1) * 5;
int nextFiveMin = ((diffMinutes * MINUTE) - (currentMinute * MINUTE)) - currentSecond;

Another approach:
private void timer1_Tick(object sender, EventArgs e)
{
// from the current time, strip the seconds, then add one minute:
DateTime dt = DateTime.Today.Add(new TimeSpan(DateTime.Now.Hour, DateTime.Now.Minute, 0)).AddMinutes(1);
// keep adding minutes until it's a multiple of 5
while (dt.Minute % 5 != 0)
{
dt = dt.AddMinutes(1);
}
// display how much time until the next five minute mark:
TimeSpan t = dt.Subtract(DateTime.Now);
fiverLabel.Text = t.ToString(#"mm\:ss");
}

Related

Edit timer number format

I have a code like this:
private IEnumerator RunTimer(float time, int kind_of_function)
{
var seconds = (int) time;
while (time > 0)
{
yield return null;
time -= Time.deltaTime;
if ((int) time != seconds)
{
// Update the text
seconds = (int) time;
timerText.text = string.Format("{0:00}:{1:00}", seconds / 60, seconds % 60);
}
if (seconds == 0)
{
}
}
}
How to change this output format: 0:00 In such a way that if the number of seconds was two-digit then it would look like 00, and if it was one-digit then 0?
As said use one of
#0 where
0 means: I definitely want this digit always
# means: I want this digit only if it is not 0 or is a significant 0
see Custom Numeric Format Strings
D
which basically means: Only show significant decimals digits.
Since you have int you could even also use N which usually includes digits after the comma
see Standard Numeric Format strings
Simply do not define a special format at all.
What you describe is what happens by default anyway if you simply used
string.Format("{0}:{1}", seconds / 60, seconds % 60)
Then I would prefer $ string interpolation which in my opinion is more flexible and better maintainable
timeText.text = $"{seconds / 60}:{seconds % 60}";
or with the formatter
timeText.text = $"{seconds / 60:#0}:{seconds % 60:#0}";
Though in my humble opinion you should stick to what you had. Doesn't it look way better?
Okey apparently what you actually wanted is not displaying the minutes at all if there are only seconds
var minutes = seconds / 60;
if(minutes > 0)
{
timeText.text = $"{minutes}:{seconds % 60:#0}";
}
else
{
timeText.text = $"{seconds:#0}";
}
private IEnumerator RunTimer(float time)
{
var seconds = (int) time;
while (time > 0)
{
yield return null;
time -= Time.deltaTime;
bool moreThanTenSec = time / 10 > 1;
if ((int) time != seconds)
{
// Update the text
seconds = (int) time;
if (moreThanTenSec)
timerText.text = string.Format("{0:00}:{1:00}", seconds / 60, seconds % 60);
else
timerText.text = string.Format("{0:00}:{1:0}", seconds / 60, seconds % 60);
}
if (seconds == 0)
{
}
}

Countdown timer going in minus instead of stopping on 0 days 00:00:00

I am dealing with this code for countdown timer in asp.net, jQuery, C#.
I have this jQuery code for the countdown timer:
<div id="timelabel"></div>
<script type="text/javascript">
var leave = <%=seconds %>;
CounterTimer();
var interv = setInterval(CounterTimer,1000);
function CounterTimer()
{
var day = Math.floor(leave / ( 60 * 60 * 24))
var hour = Math.floor(leave / 3600) - (day * 24)
var minute = Math.floor(leave / 60) - (day * 24 *60) - (hour * 60)
var second = Math.floor(leave) - (day * 24 *60*60) - (hour * 60 * 60) -(minute*60)
hour = hour < 10 ? "0" + hour : hour;
minute = minute < 10 ? "0" + minute : minute;
second = second<10 ? "0" + second : second;
var remain = day + " days " + hour + ":" + minute + ":" + second;
leave = leave - 1;
document.getElementById("timelabel").innerText = remain;
}
</script>
And I am passing end date from code behind file that is .cs:
public double seconds;
protected void Page_Load(object sender, EventArgs e)
{
seconds = (GetEndTime() - GetStartTime()).TotalSeconds;
}
private DateTime GetStartTime()
{
return DateTime.Now;
}
private DateTime GetEndTime()
{
return new DateTime(2016, 6, 12, 11, 57, 00); //end date yr-month-day hr-mnt-sec
}
I am facing a problem that this timer wont stops when it hits 0 days 00:00:00
it goes beyond that like -1 days 23:48:20. I want to fix this as I don't have that much knowledge about jQuery I am finding it pretty difficult so can someone guide me with needed modifications? Please help. Thank you in advance.
You need to clear interval after it goes to 0 or beyond. Add this to the bottom of your CounterTimer function.
if(leave <= 0) clearInterval(interv);

C# Console application, How to calculate Mobile Bill for any duration?

Lets say We have two billing period for our mobile call, if we call between 0-12, then call rate is 1$/Min & if we call between 12-24, then the rate is 2$/min. A call can starts at any time & lasts for any duration. I need to calculate the bill for the call duration. I'm getting it difficult to work with the datetime type. Also I need a better algorithm to calculate the bill. I'm trying something like this:
DateTime StartTime, EndTime;
decimal Bill = 0;
decimal RemainingDuration;
StartTime = DateTime.Now;
EndTime = DateTime.Now.AddHours(2.5);
var Duration = (EndTime.ToString("H:mm") - StartTime.ToString("H:mm"));
if (StartTime.Hour > 0 && StartTime.Hour < 12)
{
//var RemainingTime = 12.00 - StartTime;
//if (Duration < RemainingTime)
//{
// Bill = (Duration * 60) * 1;
// Console.WriteLine(Bill);
//}
//else
//{
// RemainingDuration = Duration - RemainingTime;
// Bill = ((RemainingTime * 60) * 1) + ((RemainingDuration * 60) * 2);
// Console.WriteLine(Bill);
//}
}
else if (StartTime.Hour > 12 && StartTime.Hour < 24)
{
//var RemainingTime = 24.00 - StartTime.Hour;
//if (Duration < RemainingTime)
//{
// Bill = (Duration * 60) * 2;
// Console.WriteLine(Bill);
//}
//else
//{
// RemainingDuration = Duration - RemainingTime;
// Bill = ((RemainingTime * 60) * 2) + ((RemainingDuration * 60) * 1);
// Console.WriteLine(Bill);
//}
}
Console.ReadLine();
There are some errors for type miss match. the errors are not my prime concern here, I wrote this code assuming the call duration can be maximum 24 hours. I need to write it for unlimited duration. Also Getting hard time to convert types. Code sample would really help. thanks
You're getting a type mismatch since you're converting the DateTime to strings before attempting arithmetic on them. As for the algorithm, well, of course there are thousands of ways you could do it, but here is a simple example that solves your 24 hour problem and perhaps gives you some more ideas.
decimal bill = 0;
DateTime startTime = DateTime.Now;
DateTime endTime = DateTime.Now.AddHours(2.5);
DateTime timeNow = startTime;
while (timeNow <= endTime)
{
decimal rate = (timeNow.Hour >= 12 && timeNow.Hour <= 24) ? 2 : 1;
bill = bill + rate;
Console.WriteLine("{0:HH:mm}, rate: ${1:#,0.00}, bill: ${2:#,0.00}", timeNow, rate, bill);
timeNow = timeNow.AddMinutes(1);
}
Console.WriteLine("Bill: {0:HH:mm} to {1:HH:mm}, {2:#,0} mins, ${3:#,0.00}", startTime, endTime, (endTime - startTime).TotalMinutes, bill);
Console.ReadLine();

C# - knowing time

This is my code:
IdleTime = System.Environment.TickCount - LastInput.dwTime;
int hour = ((IdleTime + 500) / 86400000);
int min = ((IdleTime + 500) / 60000) - (hour * 60);
int sec = ((IdleTime + 500) / 1000) - (min * 60);
I got a idle timer for this in a timer that tracks the idle time
The seconds works and the min works but im not sure if it will work once the hour hits 24 I think it might bug out on me coz 86400000 millie milliseconds is a day and I have the sec and the min getting data from the previous time like sec is gettings data from the min. Can anyone help?
I recommend that you work with the TimeSpan type to avoid doing the math yourself:
int milliseconds = Environment.TickCount - LastInput.dwTime;
TimeSpan idleTime = TimeSpan.FromMilliseconds(milliseconds + 500);
int hour = (int) idleTime.TotalHours;
int minutes = idleTime.Minutes;
int seconds = idleTime.Seconds;
I would say
IdleTime = System.Environment.TickCount - LastInput.dwTime;
int hours = IdleTime / 3600000;
int minutes = IdleTime / 60000 - hour * 60;
int seconds = IdleTime / 1000 - min * 60;
I'm not sure why you substract 500 from IdleTime.

C#: decrementing a clock using modulus math

Trying to emulate the rollover of a 24 hour clock by hand (with math vs. using the timespan classes). The incrementing part was easy to figure out how to roll over from 23:00 to 0:00 and from, but getting it to go the other way is turning out to be really confusing. Here's what I have so far:
static void IncrementMinute(int min, int incr)
{
int newMin = min + incr,
hourIncrement = newMin / 60;
//increment or decrement the hour
if((double)newMin % 60 < 0 && (double)newMin % 60 > -1)
hourIncrement = -1;
Console.WriteLine("Hour increment is {0}: ", hourIncrement);
}
The problem that im finding is when going backwards, if the the modulus of is between numbers, it will not decrement correctly. Example: it is 12:00 and you subtract 61 minutes, we know the time would be 10:59 as the hour should roll back 1 hour for going from 12:00 to 11:59, then back again for going from 11:00 to 10:59. Unfortunately the way im calculating it: newMin % 60 in this case, only grabs the first hour rollback, but since the second rollback is technically -1.0166 as a remainder, and since mod only returns a whole number, its rounding off. Im sure im missing some basic math here, but could someone help me out?
EDIT: I've written this a number of ways long and short. Some are closer than others, but I know this is simpler than it seems. I know this one seems kinda "wtf was he doing", but you should be able to see basically what Im trying to do. Incrementing a clock and having it rollover from 23:59 to 0:00 is easy. Going backwards has proven to be not so easy.
OK, here's the incrementMinute with the rollover. Simple. But try to go backwards. Doesn't work.
static void IncrementMinute(int min, int incr)
{
int newMin = min + incr,
hourIncrement = newMin / 60;
min = newMin % 60;
Console.WriteLine("The new minute is {0} and the hour has incremented by {1}", min, hourIncrement);
}
I'd go for something a bit simpler
public class Clock
{
public const int HourPerDay = 24;
public const int MinutesPerHour = 60;
public const int MinutesPerDay = MinutesPerHour * HourPerDay;
private int totalMinutes;
public int Minute
{
get { return this.totalMinutes % MinutesPerHour; }
}
public int Hour
{
get { return this.totalMinutes / MinutesPerHour; }
}
public void AddMinutes(int minutes)
{
this.totalMinutes += minutes;
this.totalMinutes %= MinutesPerDay;
if (this.totalMinutes < 0)
this.totalMinutes += MinutesPerDay;
}
public void AddHours(int hours)
{
this.AddMinutes(hours * MinutesPerHour);
}
public override string ToString()
{
return string.Format("{0:00}:{1:00}", this.Hour, this.Minute);
}
}
Sample usage :
new Clock().AddMinutes(-1); // 23:59
new Clock().AddMinutes(-61); // 22:59
new Clock().AddMinutes(-1441); // 23:59
new Clock().AddMinutes(1); // 00:01
new Clock().AddMinutes(61); // 01:01
new Clock().AddMinutes(1441); // 00:01
You might try calculating both minute and hour increments first, then handling cases where the new minutes crosses an hour boundary, something like this:
int hourIncrement = incr / 60;
int minIncrement = incr % 60;
int newMin = min + minIncrement;
if (newMin < 0)
{
newMin += 60;
hourIncrement--;
}
else if (newMin > 60)
{
newMin -= 60;
hourIncrement++;
}
Edit
I like #Ben Voigts answer, but was wondering if there would be any difference in performance. I ran the console application below to time them both, and was a little surprised by the results.
40 ms for the code above
2876 ms for Ben's answer
This was done in a release build. Can anyone else run this and confirm? Am I making any mistakes in the way I time them?
using System;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
int max = 100000000;
sw.Start();
for (int i = 0; i < max; i++)
IncrementMinute1(0, -61);
sw.Stop();
Console.WriteLine("IncrementMinute1: {0} ms", sw.ElapsedMilliseconds);
sw.Reset();
sw.Start();
for (int i = 0; i < max; i++)
IncrementMinute2(0, -61);
sw.Stop();
Console.WriteLine("IncrementMinute2: {0} ms", sw.ElapsedMilliseconds);
Console.ReadLine();
}
static void IncrementMinute1(int min, int incr)
{
int hourIncrement = incr / 60;
int minIncrement = incr % 60;
int newMin = min + minIncrement;
if (newMin < 0)
{
newMin += 60;
hourIncrement--;
}
else if (newMin > 60)
{
newMin -= 60;
hourIncrement++;
}
}
static void IncrementMinute2(int min, int incr)
{
min += incr;
int hourIncrement = (int)Math.Floor(min / 60.0);
min -= hourIncrement * 60;
}
}
}
Modular mathematics is only defined for the integers. If you are attempting to mix modular arithmetic with real numbers you will not succeed. You need to figure out a different mathematical approach.
Try
int newMin = min + incr,
hourIncrement = (int)Math.Floor(newMin / 60.0);
min -= hourIncrement * 60;
The essential problem was that you want hourIncrement to round down, but integer division rounds toward zero. They're the same with positive numbers, but not for negative...
EDIT (getting rid of useless extra variable):
min += incr;
int hourIncrement = (int)Math.Floor(min / 60.0);
min -= hourIncrement * 60;
EDIT2 (avoid floating-point arithmetic):
min += incr;
int hourIncrement = min / 60;
min -= hourIncrement * 60;
if (min < 0) { min += 60; --hourIncrement; }
Why to complicate things
public System.Timers.Timer timer = new System.Timers.Timer(1000);
public DateTime d;
public void init()
{
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
d = new DateTime(2011, 11, 11, 23, 59, 50);
d=d.AddHours(1);
Console.Writeline(d);
d=d.AddHours(-2);
Console.Writeline(d);
timer.Enabled = true;
}
void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
this.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() =>
{
MoveClockHands();
d=d.AddSeconds(1);
Console.WriteLine(d);
}));
}
void MoveClockHands() //12 hours clock
(
s=d.Second * 6;
m=d.Minute * 6;
h=0.5 * ((d.Hour % 12) * 60 + d.Minute)
}

Categories

Resources