#c Twitch bot uptime displaying unwanted milliseconds - c#

For the past day or so I've been writing a twitch bot for my channel. Before this I had no knowledge of C# so it could just be a simple fix, but I haven't found any solutions anywhere online.
The problem is that when I use !Uptime it displays the time like so, 01:20:36:1347242 (HH:mm:ss:mmmmmmm)
How would I go about removing the milliseconds when the command is run?
public static readonly DateTime Uptime = DateTime.Now;
if (message.Contains("!uptime"))
{
int result = Environment.TickCount & Int32.MaxValue;
var uptime = DateTime.Now - Program.Uptime;
var minutes = uptime.TotalMinutes;
irc.sendChatMessage("Stream uptime: " + uptime);
}

Just use the format string to display only hours, minutes and seconds:
irc.sendChatMessage($"Stream uptime: {uptime:hh\\:mm\\:ss}");
If you are not using C#6, use string.Format:
irc.sendChatMessage(string.Format("Stream uptime: {0:hh\\:mm\\:ss}", uptime));

Related

System.Threading.Timer trying to make timer for same time every day

I am using System.Threading.Timer in a console service app, and trying to make timer for same time every day.
Initially I am good if I start the app prior to the time. Like if my time is 10:05 and I start the app at 10:00 we are good. But if I start at 10:06 I dont know how to tell the timespan to go 24 hours ahead.
Thanks for any help!
public void SetUpTimer(TimeSpan alertTime)
{
DateTime current = DateTime.Now;
TimeSpan timeToGo = alertTime - current.TimeOfDay;
if (timeToGo < TimeSpan.Zero)
{
EventLog.WriteEntry("MyApp", "Timer Passed " );
return;//time already passed
}
timer = new System.Threading.Timer(x =>
{
EventLog.WriteEntry("MhyApp", "Timer Set " + timeToGo);
this.MethodRunsAt();
}, null, timeToGo, System.Threading.Timeout.InfiniteTimeSpan);
}
I suggest you to use cron expressions to solve this task. For example you can use Quartz.Net library (it is available through nuget).
Your cron expression will look like this:
0 10 * * * //“At 10:00”
It tells that action will be performed exactly “At 10:00” every day. Or if you want you can even start it every monday and wednesday:
0 10 * * 1,3 //“At 10:00 on Monday and Wednesday.”
Or if you want to make it periodic in some time scope:
0/2 10 * * 1,3 //“At every 2nd minute from 0 through 59 past hour 10 on Monday and Wednesday.”
Here's one way to do it:
public void SetUpTimer(TimeSpan alertTime)
{
DateTime targetDateTime = DateTime.Today.Add(alertTime);
if (targetDateTime < DateTime.Now)
{
targetDateTime = targetDateTime.AddDays(1);
}
TimeSpan timeToGo = targetDateTime - DateTime.Now;
timer = new System.Threading.Timer(x =>
{
EventLog.WriteEntry("MhyApp", "Timer Set " + timeToGo);
this.MethodRunsAt();
}, null, timeToGo, System.Threading.Timeout.InfiniteTimeSpan);
}

C# time subtraction Issue

I have been facing issue on time subtraction in C#.
For example I start timer on 4/5/2017 11:56:27 PM and end the timer in 5/5/2017 12:10:27 AM when I subtract this it shows me result 23 hours.
I want that it show exact time like 14 minutes. I am sharing my code as well.
double rate1 = Convert.ToDouble(rate.Text);
double value = rate1 / 3600;
DateTime dt = DateTime.Parse(text3.Text);
DateTime edt = DateTime.Parse(text5.Text);
var res = dt.Subtract(edt).ToString().Replace('-', ' ');
DateTime tt = Convert.ToDateTime(res);
DateTime dt1 = DateTime.Parse(text4.Text);
DateTime edt1 = DateTime.Parse(text6.Text);
var res1 = dt.Subtract(edt1).ToString().Replace('-', ' ');
double sec = TimeSpan.Parse(res).TotalSeconds;
double sec1 = TimeSpan.Parse(res1).TotalSeconds;
text7.Text = res.ToString();
text8.Text = res1.ToString();
It seems like you're showing a lot of code that's difficult to reproduce for us, and the variable names are not the clearest. I'm assuming dt stands for "datetime", and edt stands for "end datetime". If that's correct, then you're subtracting the end date from the start date instead of the other way around (you should subtract the smaller from the larger).
So, here's how to get the difference between start and end (I'm using Hindi culture info for this):
var dateFormatCulture = new CultureInfo("hi-IN");
var startDate = DateTime.Parse("4/5/2017 11:56:27 PM", dateFormatCulture);
var endDate = DateTime.Parse("5/5/2017 12:10:27 AM", dateFormatCulture);
var difference = endDate.Subtract(startDate);
You say you want "the exact time like 14 minutes". I'm not sure if that means you don't want to show the rest of the values, but here are a few ways you can display it.
Console.WriteLine($"General short string format: {difference:g}");
Console.WriteLine(
"Custom string format: {0} days, {1} hours, {2} minutes, {3} seconds",
difference.Days, difference.Hours, difference.Minutes, difference.Seconds);
Console.WriteLine("In terms of minutes, the total minutes difference is: {0}",
difference.TotalMinutes);
Notice that there's a difference between the second an third example in the methods being called to show the minutes . Minutes will display just the minutes portion of the difference. TotalMinutes will display the entire difference in terms of minutes. In your case they are the same, but if the difference was 1 hour and 14 minutes, Minutes would still be 14, but TotalMinutes would be 74.
The output looks like:
It looks like you might have a copy/paste error. In this line, did you mean to reference dt1 rather than dt?
var res1 = dt.Subtract(edt1).ToString().Replace('-', ' ');

Show time since post was made in asp.net mvc

I am working on a comments system and would love to show the time since the post was made instead of the actual time the post was made. Is there an easy way to do this?
Currently I pull the dateAdded
comment.DateAdded = DateTime.Now;
A few things:
Don't use DateTime.Now in a web application. The time zone of your server should be irrelevant. Since you're storing the time a post was made, you should use DateTime.UtcNow instead.
comment.DateAdded = DateTime.UtcNow;
Read: The Case Against DateTime.Now
You can then subtract the time the post was made from the current time.
TimeSpan elapsed = DateTime.UtcNow - comment.DateAdded;
Once you have a TimeSpan object, you can then use any of various methods and properties.
// to get the total hours elapsed
double hours = elapsed.TotalHours;
// to get the total minutes elapsed
double minutes = elapsed.TotalMinutes;
// to get a string output of the elapsed time in the default format
string s = elapsed.ToString();
Be careful not to mistake the Minutes and TotalMinutes properties. An elapsed time on 90 minutes will have TotalMinutes == 90.0, but Hours == 1 and Minutes == 30.
Use this HelperExtension
public static class TimeHelper{
public static string TimeSpanString(this DateTime date) {
var Now = DateTime.Now-date; //better to use DateTime.UtcNow
if(Now.Days>0){
return Now.Days+" Days "+Now.Hours+" Hours "+Now.Minutes+" Minutes";
}
if (Now.Hours > 0)
{
return Now.Hours + " Hours " + Now.Minutes + " Minutes";
}
return Now.Minutes + " Minutes";
}
}
Ex how to use it.
comment.DateAdded.TimeSpanString()

Calculate total number of Hours asp.net c#

I have done the following piece of code to add the Hours and thus calculate total number of hours.
string hour1="48.40";
string hour2 = "45.35";
TimeSpan ts = new TimeSpan(int.Parse(hour1.Split('.')[0]),int.Parse(hour1.Split('.')[1]),
0);
TimeSpan ts1 = new TimeSpan(int.Parse(hour2.Split('.')[0]),int.Parse(hour2.Split('.')[1]),
0);
Double total = (ts.TotalHours) + (ts1.TotalHours);
The problem here is when i add hour1 and hour2 the total comes as 64.25 which actually should have been 64.15
This is just one of the test case, if i put hour1= 40.00 and hour2= 40.10 than the value in the total comes as 80.166666666666657 which actually should have been 80.10
can anyone help me understand what am i doing wrong and what is the correct way to add HOUR and get total number of hours ?
Actually you're getting correct result - just mixing minutes and fractional parts of hours.
80 hrs 10 mins is 80 1/6 hours
64 hours 15 mins is 64 1/4 hours
It gets a little strange when you have timestamps put into strings. But if you need to do it like this, this code should work
string hour1="48.40";
string hour2 = "45.35";
//find total number of minutes for each hour above
int minutes1 = int.Parse(hour1.Split('.')[0])*60+int.Parse(hour1.Split('.')[1]);
int minutes2 = int.Parse(hour2.Split('.')[0])*60+int.Parse(hour2.Split('.')[1]);
//calculate back to hours and minutes and reassemble as a string
string result = (minutes1+minutes2)/60+"."+(minutes1+minutes2)%60;
And I hope you are expecting 94.15 and not 64.15 in your example above.
You may use next code to get result you would like to:
string hour1 = "48.40";
string hour2 = "45.35";
TimeSpan ts = new TimeSpan(int.Parse(hour1.Split('.')[0]), int.Parse(hour1.Split('.')[1]),
0);
TimeSpan ts1 = new TimeSpan(int.Parse(hour2.Split('.')[0]), int.Parse(hour2.Split('.')[1]),
0);
TimeSpan total = ts + ts1;
int hours = (int)total.TotalHours;
int minutes = total.Minutes;

Question about TimeZones and Jquery CountDown plugin

I am looking to use this plugin: http://keith-wood.name/countdown.html
but I need to use the TimeZone feature of it. So I was looking at the sample code
$('#sydneyCountdown').countdown({until: liftoffTime, timezone: +10});
so +10 is the TimeOffSet number. Now I need to make it so I can do a jquery get request and grab the TimeOffSet from the server(which gets the users time from the db and does TimeOffSet).
However it seems that C# TimeOffSet returns something like this "+02:00"(not this is just a random zone not the same as the one in the jquery example).
So it seems like all the C# TimeOffSet follow that format +/-xx:xx
So I don't understand why the jquery plugin is only 2 digts while the other one is 4 digits.
Can I know off safley the last 2 digits in the C# tomatch the plugin format?
Edit - would this work?
// working on how to get offsetTime will be posted soon.
string time = "-08:30";
string[] split = new string[] {":"};
string[] splited = time.Split(split, StringSplitOptions.RemoveEmptyEntries);
int hours = Convert.ToInt32(splited[0]);
int mins = Convert.ToInt32(splited[1]);
int totalMins = (hours * 60) + mins;
So just convert the hours to mins and then add the mins to it?
Edit - With offSetTime
var info = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time");
TimeSpan span = info.BaseUtcOffset;
string time = Convert.ToString(span);
string[] split = new string[] {":"};
string[] splited = time.Split(split, StringSplitOptions.RemoveEmptyEntries);
int hours = Convert.ToInt32(splited[0]);
int mins = Convert.ToInt32(splited[1]);
int totalMins = (hours * 60) + mins;
Problem though OffSet only gives me the number not the +/- sign. So I don't know how to get it.
Edit -
Never mind I it makes sense that they don't add the plus sign since I was just testing one that would have a "-" sign and it is shown.
The plugin says:
Cater for time zones with the timezone
setting, which is set to the target
time's offset from GMT, in either
hours or minutes.
So, I think based on the magnitude of the timezone value, it treats it either as hours or minutes. You should convert the <sign><hh>:<mm> format to into number of minutes, to account for timezones that are not hour-aligned. Something like:
var tz = "-08:30";
var tz_tokens = /([+\-])0?(\d+):(\d+)/.exec(tz);
var tz_minutes = (tz_tokens[1] + 1) * (tz_tokens[2] * 60 + tz_tokens[3]);
// ..., timezone: tz_minutes, ...

Categories

Resources