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()
Related
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);
}
I need to make a calculation of passed and remaining time of an operation in C#.
I have the start of the operation saved in a string format of HH:MM:SS
I have a default time length of the operation in a string format of HH:MM:SS
Now I would like to calculate:
The remaining time / extra time: For example if the operation is still below the default length, it should display -HH:MM:SS, and if the operation took longer than the default time, it should display +HH:MM:SS
If the operation took longer, I would also like to have a double value of HH,MM in % style. For example: 3hours and 30 minutes should be displayed as 3,5
Both results to be displayed next to each other.
I know I have to translate the string values into DateTime and/or TimeSpan values to do calculations, but currently I have no idea how to calculate since the first operation for example would not give me a negative value, but just get back in time [22:30:00 of yesterday].
Try this..
var start = "17:05:11"; // Pass this as a parameter
var startTime = DateTime.Parse(start);
var defaultDuration = TimeSpan.FromMinutes(2);
TimeSpan operationDuration = startTime - DateTime.Now;
TimeSpan diff = defaultDuration - operationDuration;
if (operationDuration > defaultDuration)
{
Console.Out.WriteLine($"+{diff.Hours}:{diff.Minutes}:{diff.Seconds}");
}
else
{
Console.Out.WriteLine($"-{diff.Hours}:{diff.Minutes}:{diff.Seconds}");
Console.Out.WriteLine($"{diff.Hours},{Math.Round(((double)(diff.Minutes * 100 / 60)),0, MidpointRounding.AwayFromZero)}");//example: 3hours and 30 minutes should be displayed as 3,5
}
At first save the default time as TimeSpan. Then you can take DateTime.Now and save it when the operation starts. Take another DateTime.Now later when it finished. After this point you can calculate the TimeSpan for the current operation. Then you can calculate the difference from these two TimeSpans as another TimeSpan. It can be positive or negativ and with these values you can do whatever you want.
TimeSpan defaultDuration = new TimeSpan(3, 30, 0);
DateTime begin = DateTime.Now;
//Do some work
DateTime end = DateTime.Now;
TimeSpan thisDuration = end - begin;
Console.WriteLine("Default: " + defaultDuration.ToString("hh\\:mm\\:ss"));
Console.WriteLine("This time: " + thisDuration.ToString("hh\\:mm\\:ss"));
Console.Write("Difference: ");
if (thisDuration > defaultDuration)
Console.Write("-");
Console.WriteLine((thisDuration - defaultDuration).ToString("hh\\:mm\\:ss"));
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));
How to check if 20 minutes have passed from current date?
For example:
var start = DateTime.Now;
var oldDate = "08/10/2011 23:50:31";
if(start ??) {
//20 minutes were passed from start
}
what's the best way to do this?
Thanks :)
You should convert your start time to a UTC time, say 'start'.
You can now compare your start time to the current UTC time using:
DateTime.UtcNow > start.AddMinutes(20)
This approach means that you will get the correct answer around daylight savings time changes.
By adding time to the start time instead of subtracting and comparing the total time on a TimeSpan you have a more readable syntax AND you can handle more date difference cases, e.g. 1 month from the start, 2 weeks from the start, ...
var start = DateTime.Now;
var oldDate = DateTime.Parse("08/10/2011 23:50:31");
if ((start - oldDate).TotalMinutes >= 20)
{
//20 minutes were passed from start
}
var start = DateTime.Now;
var oldDate = DateTime.Parse("08/10/2011 23:50:31");
if(start.Subtract(oldDate) >= TimeSpan.FromMinutes(20))
{
//20 minutes were passed from start
}
Parse oldDate into a DateTime object (DateTime.Parse).
Subtract the parsed date from start. This will return a TimeSpan.
Inspect TotalMinutes.
I was able to accomplish this by using a JodaTime Library in my project. I came out with this code.
String datetime1 = "2012/08/24 05:22:34";
String datetime2 = "2012/08/24 05:23:28";
DateTimeFormatter format = DateTimeFormat.forPattern("yyyy/MM/dd HH:mm:ss");
DateTime time1 = format.parseDateTime(datetime1);
DateTime time2 = format.parseDateTime(datetime2);
Minutes Interval = Minutes.minutesBetween(time1, time2);
Minutes minInterval = Minutes.minutes(20);
if(Interval.isGreaterThan(minInterval)){
return true;
}
else{
return false;
}
This will check if the Time Interval between datetime1 and datetime2 is GreaterThan 20 Minutes. Change the property to Seconds. It will be easier for you know. This will return false.
var end = DateTime.Parse(oldDate);
if (start.Hour == end.Hour && start.AddMinutes(20).Minute >= end.Minute)
i am doing a project on cab services.in this rate is different for day and night.
in the form only journey start date and end date is selected.based on this i have to calculate the no of days and nights.
here i am confused how to calculate the no of days and night.
thanks in advance.
private List<DateTime> GetDateRange(DateTime StartingDate, DateTime EndingDate)
{
if (StartingDate > EndingDate)
{
return null;
}
List<DateTime> rv = new List<DateTime>();
DateTime tmpDate = StartingDate;
do
{
rv.Add(tmpDate);
tmpDate = tmpDate.AddDays(1);
} while (tmpDate <= EndingDate);
return rv;
}
To view this code in action, copy and paste the following code into SnippetCompiler:
DateTime StartingDate = DateTime.Parse("02/25/2007");
DateTime EndingDate = DateTime.Parse("03/06/2007");
foreach (DateTime date in GetDateRange(StartingDate,EndingDate))
{
WL(date.ToShortDateString());
}
Sample output :
2/25/2007
2/26/2007
2/27/2007
2/28/2007
3/1/2007
3/2/2007
3/3/2007
3/4/2007
3/5/2007
3/6/2007
Use the Subtract method to get the difference, which is a TimeSpan value. Example:
TimeSpan diff = SecondDate.Subtract(FirstDate);
You can get the length of the time span for example in hours:
double hours = diff.TotalHours;
I'm not sure which time unit "days and nights" could be interpreted as, though. Perhaps days?
double days = diff.TotalDays;
DateTime dt1,dt2;
//...
TimeSpan period = dt1 - dt2;
int days = period.Days;
It sounds like a very long Cab journey that takes days and nights!
I think you need to define what a day and a night is more clearly in order to get your perfect answer. You also need to think about what impact Daylight Saving Time has on your calculations.
If say:
a day was the period from 6am to 6pm
the night was the rest - from 6pm to 6am
and you wanted to really count hours rather than days
In this case then a calculation would require you to:
iterate a currentDateTime from the startDateTime to the endDateTime
choose the increment in the currentDateTime so that it jumps to the next time barrier (6am, 6pm or the endDateTime)
within each loop, then add to your cumulative calculation of numDayHours or numNightHours so far.
Note that:
you could make this calculation quicker by counting whole days along the way
you need to be very careful about the time zone you are calculating in (I just hope that your taxi doesn't cross time zone boundaries!)
you need to be very careful about local time changes - especially "daylight savings time" type changes - the duration from 6pm to 6am is not always 12 hours!
Some pseudo code:
var numDayHours = 0.0;
var numNightHours = 0.0;
var current = startDateTime;
while (current < endDateTime)
{
next_hop = calculate_next_hop (current, endDateTime);
// select next date time
switch (next_hop.hop_type)
{
case HopType.night_time_hop:
numNightHours += next_hop.num_hours;
break;
case HopType.day_time_hop:
numDayHours += next_hop.num_hours;
break;
}
current = next_hop.EndDateTime;
}
// and here is the result
double numDays = numDayHours / 12.0;
double numHours = numNightHours / 12.0;