TimeSpan and ToString() - c#

I want to display minutes, seconds, and milliseconds saved in TimeSpan. It should look like this:
var d1 = new DateTime(2020, 12, 1, 12, 00, 00);
var d2 = new DateTime(2020, 12, 1, 10, 12, 30);
var d = d1 - d2;
Console.WriteLine(d.ToString(#"mm\:ss\:fff"));
But it returns 47:30:000 which is only partially true, because it ignored one hour. I want it to be converted into minutes, not ignored.

I think you need TimeSpan.TotalMinutes.
https://learn.microsoft.com/en-us/dotnet/api/system.timespan.totalminutes?view=net-7.0
In your case it could be:
Console.WriteLine($#"{(int)d.TotalMinutes}:{d:ss\:fff}");

TimeSpan has a property for getting the total number of minutes contained in it, as a double value: TimeSpan.TotalMinutes Property.
Note that if your TimeSpan's duration is not in whole minutes you will get a fraction part:
var d1 = new DateTime(2020, 12, 1, 12, 00, 00);
var d2 = new DateTime(2020, 12, 1, 10, 12, 30);
var d = d1 - d2;
Console.WriteLine(d.TotalMinutes);
Output:
107.5
Note that TimeSpan has similar properties for TotalDays, TotalHours, TotalSeconds, TotalMilliseconds.
Update:
Based on the comments below, here's a solution that prints in a format splitting minutes, seconds and milliseconds:
var d1 = new DateTime(2020, 12, 1, 12, 00, 00);
var d2 = new DateTime(2020, 12, 1, 10, 12, 30);
var d = d1 - d2;
double totalMin = d.TotalMinutes;
int totalMinInt = (int)totalMin; // will get only the whole minutes.
Console.WriteLine(totalMinInt.ToString() + // print the whole minutes part
":" +
d.ToString(#"ss\:fff")); // print the fraction part
Output:
107:30:000

Related

Calculate Business Hours

I am using following code to calculate the buiness hours
TimeRange timeRange = new TimeRange(
new DateTime(2018, 1, 08, 10, 00, 00),
new DateTime(2018, 1, 15, 15, 30, 00));
CalendarDateDiff dateDiff = new CalendarDateDiff();
dateDiff.WorkingHours.Add(new HourRange(9, 18));
dateDiff.AddWorkingWeekDays();
var calendarDateAdd = new CalendarDateAdd();
calendarDateAdd.ExcludePeriods.Add(new Day(2018, 1, 10,calendarDateAdd.Calendar));
TimeSpan nonBusinessHours = dateDiff.Difference(timeRange.Start, timeRange.End);
double businessHours = timeRange.Duration.TotalHours -nonBusinessHours.TotalHours;
return businessHours;
The details explanation is in the code project.Calculate-Business-Hours # codeproject. In that code it specify a code to add holidays . But it not correctly working as specified.
The required Nuget package is listed here
TimePeriodLibrary.NET

C# - Searching Time between 2 DateTime Objects of different days

i have a list of "event" objects.
In every event i have "EventStartTime" and "EventEndTime" declared as DateTime objects.
I want to be able to search "events" by time , for example 10:00,
the "event" you see below shows that the festival starts at 22:00 on Feb 17th,
and ends at 15:00 the following day. i have a couple more like these.
new EventsManager.Event() //3
{
EventType = EventsManager.EventType.Festival,
EventName = "Twistival",
EventPlace = placeList[4],
EventStartTime =new DateTime(2017,02,17,22,0,0),
EventEndTime = new DateTime(2017,02,18,15,0,0),
EventNumberOfParticipants = 8000
},
So when i search for event that occur, or still occurring at at 10:00
i should get this event.
any suggestions?
Assuming that you have a specific time of day that you want to determine if the event covers regardless of the date it covers it on then there are 4 cases you need to consider. First if the dates are more than 1 day apart they cover all times of day. If the start is before the time of day and the end is after the time of day it will cover the time. The last two cases require that the end date be on the next day from the start date, then either the start date is before the time of day, or the end date is after the time of day. Note that this also assumes that the start date is before the end date.
var events = new List<Tuple<DateTime, DateTime>>
{
// start and end after time of day but on different days
Tuple.Create(
new DateTime(2017, 02, 17, 22, 0, 0),
new DateTime(2017, 02, 18, 15, 0, 0)),
// start and end before time of day but on different days
Tuple.Create(
new DateTime(2017, 02, 17, 9, 0, 0),
new DateTime(2017, 02, 18, 7, 0, 0)),
// start before and end after same day
Tuple.Create(
new DateTime(2017, 02, 17, 9, 0, 0),
new DateTime(2017, 02, 17, 11, 0, 0)),
// covers more than 1 day
Tuple.Create(
new DateTime(2017, 02, 17, 22, 0, 0),
new DateTime(2017, 02, 18, 22, 0, 1)),
// start after and end before on different days
Tuple.Create(
new DateTime(2017, 02, 17, 22, 0, 0),
new DateTime(2017, 02, 18, 10, 0, 0)),
// start and end before on same day
Tuple.Create(
new DateTime(2017, 02, 17, 7, 0, 0),
new DateTime(2017, 02, 17, 8, 0, 0)),
// start and end after on same day
Tuple.Create(
new DateTime(2017, 02, 17, 11, 0, 0),
new DateTime(2017, 02, 17, 12, 0, 0)),
};
var timeOfDay = new TimeSpan(0, 10, 0 ,0);
foreach (var x in events)
{
if (x.Item2 - x.Item1 > TimeSpan.FromDays(1)
|| (x.Item1.TimeOfDay < timeOfDay && x.Item2.TimeOfDay > timeOfDay)
|| (x.Item1.Date < x.Item2.Date
&& (x.Item1.TimeOfDay < timeOfDay || x.Item2.TimeOfDay > timeOfDay)))
{
Console.WriteLine(x);
}
}
Will output
(2/17/2017 10:00:00 PM, 2/18/2017 3:00:00 PM)
(2/17/2017 9:00:00 AM, 2/18/2017 7:00:00 AM)
(2/17/2017 9:00:00 AM, 2/17/2017 11:00:00 AM)
(2/17/2017 10:00:00 PM, 2/18/2017 10:00:01 PM)
Let's say you have a
List<Event> Events;
of your Events. You can create a simple LINQ query to get all events running at a special time with a simple method like
private IEnumerable<Event> GetRunningEvents(DateTime time)
{
return Events.Where(E => E.EventStartTime <= time && E.EventEndTime >= time);
}
Dont forget to add
using System.Linq;
to your file.
EDIT: Without LINQ a possible approach is
private List<Event> GetRunningEvents(DateTime time)
{
List<Event> RunningEvents = new List<Event>();
foreach(Event E in Events)
{
if (E.EventStartTime <= time && E.EventEndTime >= time)
{
RunningEvents.Add(E);
}
}
return RunningEvents;
}
Try Linq Where:
var list = new List<Event>();
var searchTime = DateTime.Now;
var result = list.Where(e => e.EventStartTime <= searchTime && searchTime <= e.EventEndTime).ToList();

How can i find all the times between two given dates and time? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
private void GetTimeBetween()
{
DateTime a = new DateTime(2010, 04, 24, 13, 10, 00);
DateTime b = new DateTime(2010, 04, 25, 13, 10, 00);
Console.WriteLine(b.Subtract(a).TotalMinutes);
double d = b.Subtract(a).TotalMinutes;
}
I'm getting TotalMinutes 1440
But how can i make now that it will create a List with all the dates and time between this two dates between a and b but in jumps of 10 minutes ?
For example in the List the first item will be:
24/4/2010 13:10:00
Then ext item will be
24/4/2010 13:20:00
And so on until b
25/4/2010 13:10:00
In this format in the List or in other formats but the idea to get all the dates+time between the two given dates.
Gee, sometimes its fun to overengineer things. There is an Aggregate function which turns a list into a scalar value - lets create one that goes the other way
public static class Extensions
{
public static IEnumerable<T> Explode<T>(this T value, Func<T,T> next, Func<T,bool> limit)
{
var n = value;
while(!limit(n))
{
yield return n;
n = next(n);
}
}
}
Usage:
DateTime a = new DateTime(2010, 04, 24, 13, 10, 00);
DateTime b = new DateTime(2010, 04, 25, 13, 10, 00);
var result = a.Explode(x => x.AddMinutes(10), x => x>b).ToList();
Live example: http://rextester.com/WCGZL87983
You could loop it:
var list = new List<DateTime>();
var start = new DateTime(2010, 04, 24, 13, 10, 00);
var end = new DateTime(2010, 04, 25, 13, 10, 00);
for (DateTime date = start; date <= end; date = date.AddMinutes(10))
list.Add(date);
Try this
var start = new DateTime(2010, 04, 24, 13, 10, 00);
var end = new DateTime(2010, 04, 25, 13, 10, 00);
for (DateTime date = start; date <= end; date = date.AddMinutes(10))
{
Console.WriteLine(date.ToString("dd/mm/yyyy HH:mm:ss"));
}

Find difference between DateTimes in List [duplicate]

This question already has answers here:
Showing Difference between two datetime values in hours
(8 answers)
Closed 8 years ago.
I have a List of DateTimes
var times = CurrentMeter.SessionTimes.ToList();
How do I find the difference between them and add the results to a new List?
I want the hours, minutes, seconds and milliseconds between each datetime.
A difference between two DateTime objects is a TimeSpan.
This function will calculate the time delta between each consecutive pair of DateTimes.
It will iterate through each time in times, subtract the previous value from it, and add the difference to your result list.
IEnumerable<TimeSpan> CalculateDeltas(IEnumerable<DateTime> times) {
var time_deltas = new List<TimeSpan>();
DateTime prev = times.First();
foreach (var t in times.Skip(1)) {
time_deltas.Add(t - prev);
prev = t;
}
return time_deltas;
}
Here's an example to calculate the difference between each item in the list. The results are stored in a List<double> and represent the total of seconds between each datetime.
var times = new List<DateTime>
{
new DateTime(2014, 5, 28, 9, 57, 12),
new DateTime(2014, 5, 28, 9, 57, 43),
new DateTime(2014, 5, 28, 9, 58, 03),
new DateTime(2014, 5, 28, 9, 59, 46),
new DateTime(2014, 5, 28, 10, 0, 22),
};
var differences = new List<double>();
for(int i = 0; i < times.Count - 1; i++)
{
differences.Add((times[i+1] - times[i]).TotalSeconds);
}
Output:
31
20
103
36
How about:
var time = new []{
DateTime.Parse("14-4-2012 00:00:00"),
DateTime.Parse("14-4-2012 01:12:34"),
DateTime.Parse("14-4-2012 12:44:33"),
DateTime.Parse("14-4-2012 23:12:42"),
};
var result = time.Zip(time.Skip(1), (a, b) => b - a)
.Select(d => new {d.Hours, d.Minutes, d.Seconds})
.ToList();
result is now:
(Note that this is a very simply approach and only works for differences < 24h. If you have greater differences, take into account d.Days etc.)

Group DateTime by an arbitrary time interval

I have an IEnumerable of an item class defined like this:
public class Item {
public DateTime Date { get; private set; }
public decimal? Value { get; private set; }
public Item(DateTime date, decimal? value) {
Date = date;
Value = value;
}
}
These items are in a specific time interval (5 minutes for exemple). I need to group them by the date, but changing the interval. For example, if the items are in the following order:
2010-08-24 00:05
2010-08-24 00:10
2010-08-24 00:15
2010-08-24 00:20
2010-08-24 00:25
2010-08-24 00:30
and I want to group them into a 15 minutes interval, the result should look like this:
2010-08-24 00:15
2010-08-24 00:30
The interval is provided by another class, but I can get the milliseconds that represent that interval (for example, Interval.FromMinutes(5).GetMilliseconds() should return 300000). The question is how can I write a grouping function that allows me to do something like this : data = items.GroupBy(t => GroupingFunction(t.DateTime, interval)) and obtain that result?
Update: the interval will not be necessarily in minutes. It could be in hours, minutes or even days.
Something like this ?
DateTime[] dateTimes = new[]
{
new DateTime(2010, 8, 24, 0, 5, 0),
new DateTime(2010, 8, 24, 0, 10, 0),
new DateTime(2010, 8, 24, 0, 15, 0),
new DateTime(2010, 8, 24, 0, 20, 0),
new DateTime(2010, 8, 24, 0, 25, 0),
new DateTime(2010, 8, 24, 0, 30, 0)
};
TimeSpan interval = new TimeSpan(0, 15, 0); // 15 minutes.
var groupedTimes = from dt in dateTimes
group dt by dt.Ticks/interval.Ticks
into g
select new {Begin = new DateTime(g.Key*interval.Ticks), Values = g.ToList()};
foreach (var value in groupedTimes)
{
Console.WriteLine(value.Begin);
Console.WriteLine("\t{0}", String.Join(", ", value.Values));
}
data = items.GroupBy(t => (int)(t.DateTime.Minutes/interval)))
Have you tried grouping by a modulus?
Untested stream-of-consciousness pseudocode follows:
data = items.GroupBy(t => t.TimeInterval % 15 == 0);

Categories