how to remove date from datetime in Linq c# - c#

i want to get only time from a datetime variable in linq query.
for eaxample if i have an array of datetime having values
["02/12/1970 14:52:06","14/06/2015 12:32:44"]
then how to extract minimum time from it so that i get output like
"12:32:44"
as if i take minimum these two it will give output
"14:52:44" instead of "12:32:44"
as the datepart of first value is smaller than the other.
i try this code:
time1 = table1.Min(x=>x.StartTime)
but it will give "14:52:06" as output
any suggestions?

First extract Time from DateTime and then get Min value
var dates = new List<DateTime>
{
new DateTime(2020, 6, 9, 12, 35, 45),
new DateTime(2020, 6, 10, 11, 35, 45)
};
var minTime = dates
.Select(d => d.TimeOfDay)
.Min();
#Update
If you want to get DateTime object that has the smallest time part, then use this:
var dateWithMinTime = dates
.OrderBy(d => d.TimeOfDay)
.FirstOrDefault();

Try
table1.Min(c => c.StartTime.TimeOfDay)
assuming StarTime is a DateTime.

Related

Get closest day in future in a LINQ expression

I have date list in yyyy/mm/dd:
2020/06/10
2020/06/18
2020/07/17
and given date
2020/06/10
I want to find closest day in future from the given date in LINQ (expected result: 2020/06/18).
If you mean to find the closest date in future then you can filter out all earlier dates (including the same date), order it and then take the first value:
List<DateTime> allDates = new List<System.DateTime>()
{
new DateTime(2020, 06, 10),
new DateTime(2020, 06, 18),
new DateTime(2020, 07, 17),
};
DateTime givenDate = new DateTime(2020, 06, 10);
DateTime closestDateInFuture = allDates.Where(x => x > givenDate).OrderBy(x=> x).First();
Console.WriteLine(closestDateInFuture);
Output:
18.06.2020 00:00:00
Another suggestion by #Johnathan Barclay is to use the Min method, which yields the same result:
DateTime closestDateInFuture = allDates.Where(x => x > givenDate).Min()

How to check if DateTime Value is before a specific DateTime in LINQ

I have this LINQ query :
var post = _db.Posts.Where(m => m.CreateDate < **13.12.2016 Hour : 18:30**)
I don't know how to set the DateTime there. How can I do that? Thanks.
You need to construct DateTime object with the date you have. You can do it in one of the following ways.
One way of doing it is..
var post = _db.Posts.Where(m => m.CreateDate < (new DateTime(2016,12,13,18,30,0)))
Another way is
var post = _db.Posts.Where(m => m.CreateDate < DateTime.Parse("13/12/2016 18:30"))
You can use the constructor of the DateTime class to build the required date by specifying the values(year,month,day,hour,minute,second), then use that datetime-Object in your Linq query for performing the comparison. which will give you the expected result:
Try this :
DateTime limitDate = new DateTime(2016, 12, 13, 18, 30, 00);
var post = _db.Posts.Where(m => m.CreateDate < limitDate);
Or else you can create the DateTimeObject by parsing some string inputs that's your Datelimit

C# Sorting DateTime issue

I am setting up a list of date times:
DateTime a1
DateTime a2
DateTime a3
DateTime a4
The above looks like this (as DateTime objects):
3/1/2012 10:56
3/1/2012 17:03
3/1/2012 1:38
3/1/2012 5:33
Then I put them in a list and sort:
List<DateTime> ldtBites = new List<DateTime>();
ldtBites.Add(a1);
ldtBites.Add(a2);
ldtBites.Add(a3);
ldtBites.Add(a4);
ldtBites.Sort();
After Sorting I get this:
3/1/2012 1:38:00 AM
3/1/2012 10:56 AM
3/1/2012 5:03:00 PM
3/1/2012 5:33:00 AM
You omitted the definition of w,x,y,z. I defined them as such:
DateTime w = new DateTime(2012, 3, 1, 10, 56, 0);
DateTime x = new DateTime(2012, 3, 1, 17, 3, 0);
DateTime y = new DateTime(2012, 3, 1, 1, 38, 0);
DateTime z = new DateTime(2012, 2, 29, 17, 3, 0);
This causes them to match your values for a1-a4; however, when I run the rest of your code, they sort correctly (a3, a4, a1, a2).
However, I noticed that x and z were the same hour/minute, so my initial test had this:
DateTime z = new DateTime(2012, 3, 1, 17, 3, 0);
When I ran this, I got them to come out in the order you were showing (a3, a1, a2, a4); however, after the AddHours() call went through, the z value was actually 3/2/2012, which is why it was last.
You don't want to convert back and forth. Just do it once. Sort your list first, and only then convert to string.
Converting to string and converting back might cause that result. Why don't you add x,y,w,z to your list directly?
List<DateTime> ldtBites = new List<DateTime>();
ldtBites.Add(DateTime.Parse("3/1/2012 10:56"));
ldtBites.Add(DateTime.Parse("3/1/2012 17:03"));
ldtBites.Add(DateTime.Parse("3/1/2012 1:38"));
ldtBites.Add(DateTime.Parse("3/1/2012 5:33"));
ldtBites.Sort();
foreach (DateTime dt in ldtBites)
Console.WriteLine(dt);
Output:
3/1/2012 1:38:00 AM
3/1/2012 5:33:00 AM
3/1/2012 10:56:00 AM
3/1/2012 5:03:00 PM
Press any key to continue . . .
Above will work only if all the date are same, in case the date are also different you should do the following...
var sortedDates = dates.OrderByDescending(x => x);
or else Don't want to use, or don't know Linq then you can go for following..
static List SortAscending(List list)
{
list.Sort((a, b) => a.CompareTo(b));
return list;
}
static List SortDescending(List list)
{
list.Sort((a, b) => b.CompareTo(a));
return list;
}

Linq group month by quarters

Is it possible to do a linq group by and group months into quarters, Ie Q1 Jan to apr etc etc
Something like this
Enumerable.Range(1,12)
.Select(o => new DateTime(DateTime.Today.Year, o, 1))
.GroupBy(o => (o.Month - 1) / 3)
Here's a basic example demonstrating this:
var dates = new[]
{
new DateTime(2011, 12, 25),
new DateTime(2011, 11, 25),
new DateTime(2011, 5, 4),
new DateTime(2011, 1, 3),
new DateTime(2011, 8, 9),
new DateTime(2011, 2, 14),
new DateTime(2011, 7, 4),
new DateTime(2011, 11, 11)
};
var groupedByQuarter = from date in dates
group date by (date.Month - 1)/3
into groupedDates
orderby groupedDates.Key
select groupedDates;
foreach(var quarter in groupedByQuarter)
{
Console.WriteLine("Q: {0}, Dates: {1}", quarter.Key, string.Join(", ", quarter));
}
The order by is there to simply help the quarters be logically ordered. You can remove the whole clause following the group statement.
With the output of:
Q: 0, Dates: 1/3/2011 12:00:00 AM, 2/14/2011 12:00:00 AM
Q: 1, Dates: 5/4/2011 12:00:00 AM
Q: 2, Dates: 8/9/2011 12:00:00 AM, 7/4/2011 12:00:00 AM
Q: 3, Dates: 12/25/2011 12:00:00 AM, 11/25/2011 12:00:00 AM, 11/11/2011 12:00:00 AM
Obviously you will need to correct the quarter numbers by adding one or perhaps translating them to a corresponding enum.
you can divide an arbitrary list into parts using an overload of the Select method and GroupBy. In your case, assuming the months in the list are in the correct order, the following should work:
var groups = yourList
.Select((item, index) => new { item, index })
.GroupBy(indexedItem=>indexedItem.index/3);
Yes it can be achieved with the LINQ to SQL GroupBy function if you define the qouters somewhere in your database or you can write some code that will handle this action it all depends on what data is available to you for this evaluation.

Data Time Format(Duration)

I have a query like i want to show the time information in custom format like(1min 06sec) from date .I have a filed Duration in database and when i am binding my data control then in item i want to display in above format(1min 06 sec),so is it possible?
Checkout this documentation - http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
But, assuming you have a DateTime object, something like this should do the trick:
var test1 = DateTime.UtcNow.ToString("m'min 's'sec'");
Or for a TimeSpan:
var test2 = TimeSpan.FromSeconds(123).ToString("m'min 's'sec'");
You can easily add in hours/days/etc. depending on the exact format you want. If your object isn't a DateTime or TimeSpan object, you will have to do something custom.
You can use System.TimeSpan structure. It represents time interval.
MSDN
Given you DateTime variable, you could do the following:
var rr = dt1.ToString("mm'min 'ss'sec'");
Or if you have a TimeSpan:
You'll need to use a TimeSpan for this. A simplistic approach is the following:
var ts = new TimeSpan(0, 2, 30);
var result = ts.Minutes.ToString() + "min " + ts.Seconds.ToString() + "sec";
In this example, I've set the TimeSpan variable to 2 minutes and 30 seconds.
Or if you have two dates:
If you have two dates you can do a diff and get the timespan and from there use the code I've shown above:
var dt1 = new DateTime(2011, 01, 01, 12, 01, 00);
var dt2 = new DateTime(2011, 01, 01, 12, 03, 30);
var diffTimeSpan = dt2.Subtract(dt1);
var r = diffTimeSpan.Minutes.ToString() + "min " + diffTimeSpan.Seconds.ToString() + "sec";

Categories

Resources