I want to divide time in equal intervals in C#. Like from 3:00pm to 6:00pm create time intervals with a gap of 45 minutes (e.g, 3:00pm, 3:45pm, 4:30pm .... 6:00pm.
How can I acheive this in C# ?
You can use the DateTime.Ticks property to define your intervals, and then create a series of DateTime objects based on your defined interval. The example below can be run in LINQpad. Per the documentation, there are 10000000 ticks in one second. With that in mind:
var startTS = Convert.ToDateTime("6/17/2018 15:00:00");
var endTS = Convert.ToDateTime("6/17/2018 18:00:00");
long ticksPerSecond = 10000000;
long ticksPerMinute = ticksPerSecond * 60;
long ticksPer45Min = ticksPerMinute * 45;
long startTSInTicks = startTS.Ticks;
long endTsInTicks = endTS.Ticks;
for(long i = startTSInTicks; i <= endTsInTicks; i+=ticksPer45Min)
{
new DateTime(i).Dump();
}
In LINQpad, the output looks like this:
6/17/2018 15:00:00
6/17/2018 15:45:00
6/17/2018 16:30:00
6/17/2018 17:15:00
Try this
DateTime StartTime = DateTime.Parse("3:0:0");//If pm it should be 15
DateTime EndTime = DateTime.Parse("6:0:0");//If pm it should be 18
while (StartTime!=EndTime)
{
double minuts = +45;
StartTime = StartTime.AddMinutes(minuts);
}
Hope this helps
Datetime.AddMinutes(double value) should do what you are looking for. Just keep on adding until the result of the addition goes over the maximum date/time you have.
NOTE: This assumes you know your interval. If, on the other hand, you require to split a time span in a equal n parts you would require a different approach, as shown here.
Related
I'm working on an asp.net core MVC project. This project about identifying online and offline users, I have two datetime, one of the stores in a database, and another is current datetime, and I must know that time stored in a database elapsed from 61 seconds or not?
I subtract two Datetime and finally use TotalSeconds property.but my output is -22095 or 2319208 and so on.
public void CheckUserStatus()
{
DateTime now = DateTime.Now;
var userTime = _context.Sessions.Where(x => x.LastOnline).Select(x => new {x.LastConnectTime, x.Id});
foreach (var time in userTime)
{
TimeSpan diffrence = now.Subtract(time.LastConnectTime);
int mytime = Convert.ToInt32(diffrence.TotalSeconds);
if ( mytime < 61)
{
Console.WriteLine(time.Id);
}
}
}
I expect out of time base on seconds, for example, right now my output is -22095 or 2319208, and so on but I don't know 2319208 is a regular time or not?
You can easily check that like this :
DateTime now = DateTime.Now;
TimeSpan past = now - now.Subtract(TimeSpan.FromSeconds(60));
TimeSpan post = now - now.Subtract(TimeSpan.FromSeconds(61));
Console.WriteLine(now);
// Should be False: Passed time is less than 60 seconds
Console.WriteLine(past.TotalSeconds > 60);
// Should be True: Passed time is more than 60 seconds
Console.WriteLine(post.TotalSeconds > 60);
I have to find out the limits of interval i.e upper-bound and lower-bound of an interval based on interval type when datetime is given.
Example: say given time = 12:05 (then, this lies in the interval range 12:00 - 1:00 if interval type is hourly; 12:00 - 12:30 if interval type is half-an hour based;
12:00 - 12:15 if interval type is quarterly. likewise interval type can be anything.
Currently i am loading all different set of interval ranges in a dictionary object on an application load and then i fetch interval range from this dictionary for the given time.
Sorry, I know this problem statement looks simple but couldn't think of other approaches as of now. It would be helpful if someone can help me here. Thanks in advance.
You can calculate the range start by dividing the total minutes by your interval and then subtracting the remainder from the total minutes. After that, you can easily get the end of the range.
First, you need to get the time part from your DateTime object as TimeSpan by using DateTime.TimeOfDay. Then use TimeSpan.TotalMinutes.
Here's a good start:
public class TimeRange
{
public TimeRange(TimeSpan from, TimeSpan to)
{
From = from;
To = to;
}
public TimeSpan From { get; set; }
public TimeSpan To { get; set; }
}
public TimeRange GetRange(DateTime d, int minutesInterval)
{
TimeSpan time = d.TimeOfDay;
var from = time.TotalMinutes - (time.TotalMinutes % minutesInterval);
var to = from + minutesInterval;
return new TimeRange(TimeSpan.FromMinutes(from), TimeSpan.FromMinutes(to));
}
For clarity, I created a simple class called TimeRange to represent the start and end of the interval range. You can, however, feel free to handle this in a different way.
Usage:
DateTime d = DateTime.Now;
TimeRange range = GetRange(d, 60);
//TimeRange range = GetRange(d, 15);
Console.WriteLine("From: {0}\r\nTo: {1}", range.From, range.To);
Try it online.
I'm calling an update function to draw a real time simulation and was wondering if there was an effective way to get the number of milliseconds passed since the last update? At the moment I have a DispatchTimer calling at regular intervals to update the simulation but the timing isn't accurate enough and ends up being about 60% slower than it should be (it varies).
I would use Stopwatch.GetTimestamp() to get a tick count, then compare the value before and after. You can convert this to timings by:
var startTicks = Stopwatch.GetTimestamp();
// Do stuff
var ticks = Stopwatch.GetTimestamp() - startTicks;
double seconds = ticks / Stopwatch.Frequency;
double milliseconds = (ticks / Stopwatch.Frequency) * 1000;
double nanoseconds = (ticks / Stopwatch.Frequency) * 1000000000;
You could also use var sw = Stopwatch.StartNew(); and sw.Elapsed.TotalMilliseconds afterwards if you just want to time different chunks of code.
Keep a variable that will not reset between calls.
Yours may not need to be static like mine.
private static DateTime _LastLogTime = DateTime.Now;
Then within the method:
// This ensures only the exact one Tick is used for subsequent calculations
// Instead of calling DateTime.Now again and getting different values
DateTime NewTime = DateTime.Now;
TimeSpan ElapsedTime = NewTime - _LastLogTime;
_LastLogTime = NewTime;
string LogMessage = string.Format("{0,7:###.000}", ElapsedTime.TotalSeconds);
I only needed down to the thousandth of a second within my string, but you can get much more accurate with the resulting TimeSpan.
Also there is a .TotalMilliseconds or even .Ticks(the most accurate) value available within the resulting TimeSpan.
I have a table of datetime and values. The value is a volume of a tank at the datetime. I want to calculate how much the tank filled / emptied in every hour during the last 10 days.
I measure the tank every 15 minutes, but maybe I will measure it every 20 minutes in the future. I am trying to calculate it using LINQ.
What I did is:
allDataView.RowFilter = String.Format(CultureInfo.InvariantCulture.DateTimeFormat,
"DateOfData < #{0}# AND DateOfData > #{1}#", DateTime.Now, DateTime.Now.AddDays((-1) * daysInterval));
allDataView.Sort = "DateOfData DESC";
// making the diff between every sample during the last daysInterval days and put it into a list with these differences.
var result = allDataView.Table.AsEnumerable().Zip(allDataView.Table.AsEnumerable().Skip(1), (row1, row2) => Convert.ToDouble(row1["Value"])-Convert.ToDouble(row2["Value"]));
But these are differences between every measurement. What I want is to calculate the differences between samples in round times during that days period.
For example:
9:50 0.5
10:05 1
10:20 2
10:35 2.5
10:50 3
11:05 5
Than I want to take the latest value that was in 11:00 (3) and take the last value that was in 10:00 (0.5) and to insert it 3-0.5 = 2.5 to a list and continue during that time period.
I want to do it using Linq. Appreciate any help how to implement it.
Thanks a lot.
I think I made it:
var groups = from row in allDataView.Table.AsEnumerable()
group row by new { Convert.ToDateTime(row["DateOfData"]).Hour, Convert.ToDateTime(row["DateOfData"]).Date } into g
select new
{
FirstDate = g.First()["DateOfData"],
FirstValue = g.First()["Value"],
LastDate = g.Last()["DateOfData"],
LastValue = g.Last()["Value"]
};
var result = groups.Select(grp => Convert.ToDouble(grp.FirstValue) - Convert.ToDouble(grp.LastValue));
I'ld recommend creating an sp to handle the grouping of the date time values. This should have the added bonus of allowing your query to run quicker, you shoukld then be able to pull the results out faster via linq.
I have a datagridview in my application which holds start and finish times. I want to calculate the number of minutes between these two times. So far I have got:
var varFinish = tsTable.Rows[intCellRow]["Finish Time"];
TimeSpan varTime = (DateTime)varFinish - (DateTime)varValue;
int intMinutes = TimeSpan.FromMinutes(varTime);
But the last line won't compile because it says I am using invalid arguments for the Timespan constructor. I've researched quite a bit about how to calculate the number of minutes between two times, but I'm hitting a bit of a brick wall. Can someone please advise me on the best way to achieve my objective.
EDIT/
Now my code is as follows:
var varFinish = tsTable.Rows[intCellRow]["Finish Time"];
TimeSpan varTime = (DateTime)varFinish - (DateTime)varValue;
int intMinutes = (int)varTime.TotalMinutes;
But I am getting an invalid cast on the second line. Both varFinish and varValue are times e.g. 10:00 and 8:00 say. So not sure why they won't cast to type DateTime?
Try this
DateTime startTime = varValue
DateTime endTime = varTime
TimeSpan span = endTime.Subtract ( startTime );
Console.WriteLine( "Time Difference (minutes): " + span.TotalMinutes );
Edit:
If are you trying 'span.Minutes', this will return only the minutes of timespan [0~59], to return sum of all minutes from this interval, just use 'span.TotalMinutes'.
double minutes = varTime.TotalMinutes;
int minutesRounded = (int)Math.Round(varTime.TotalMinutes);
TimeSpan.TotalMinutes: The total number of minutes represented by this instance.
In your quesion code you are using TimeSpan.FromMinutes incorrectly. Please see the MSDN Documentation for TimeSpan.FromMinutes, which gives the following method signature:
public static TimeSpan FromMinutes(double value)
hence, the following code won't compile
var intMinutes = TimeSpan.FromMinutes(varTime); // won't compile
Instead, you can use the TimeSpan.TotalMinutes property to perform this arithmetic. For instance:
TimeSpan varTime = (DateTime)varFinish - (DateTime)varValue;
double fractionalMinutes = varTime.TotalMinutes;
int wholeMinutes = (int)fractionalMinutes;
You just need to query the TotalMinutes property like this varTime.TotalMinutes
If the difference between endTime and startTime is greater than or equal to 60 Minutes , the statement:endTime.Subtract(startTime).Minutes; will always return (minutesDifference % 60). Obviously which is not desired when we are only talking about minutes (not hours here).
Here are some of the ways if you want to get total number of minutes(in different typecasts):
// Default value that is returned is of type *double*
double double_minutes = endTime.Subtract(startTime).TotalMinutes;
int integer_minutes = (int)endTime.Subtract(startTime).TotalMinutes;
long long_minutes = (long)endTime.Subtract(startTime).TotalMinutes;
string string_minutes = (string)endTime.Subtract(startTime).TotalMinutes;