how to get a date from a datetime offset in linq - c#

I have a table that has date time stored as follows
2022-02-01 17:47:50.3483971 +00:00
2022-05-11 18:47:50.3483971 +00:00
2022-05-21 14:40:50.3483971 +00:00
I'm trying to write a linq query that will compare get results for the date passed but i only want to pass in the date, for example get the records from 2022/02/01
so I tried
var fdate= query.filteredDate.LocalDateTime.ToShortDateString(); // this gets the date the user passes in.
the problem comes in the where clause when I try this
filteredResult.Where(x=> fdate >= DateTime.Parse(x.storeddate.LocalDateTime.ToShortDateString()))
then it errors out and says can not be applied to string and datetime
so I tried this
Where(x=> fdate >= x.storeddate.LocalDateTime.ToShortDateString()))
and it says can not be applied to string and string
what am I doing wrong?

here I've write an some code to resolve your issue:
List<DateTime> ListDatesToCompare = new List<DateTime>(); //that list simulate your input list
ListDatesToCompare.Add(new DateTime(2022, 02, 01, 17, 47, 50, 348, DateTimeKind.Utc));
ListDatesToCompare.Add(new DateTime(2022, 05, 11, 18, 47, 50, 348, DateTimeKind.Utc));
ListDatesToCompare.Add(new DateTime(2022, 05, 21, 14, 40, 50, 348, DateTimeKind.Utc));
//this is your filter in string format
string fdate = "2022/02/01";
//for this example i've forced the culture info to be sure that the date will be correctly parsed (here some documentation: https://stackoverflow.com/questions/13797727/datetime-and-cultureinfo)
DateTime fDateParsed = DateTime.Parse(fdate, new System.Globalization.CultureInfo("en-EN"));
//here the result query
List<DateTime> ResultOfQuery = ListDatesToCompare.Where((DateTime CurrentDT) =>
{
//you can do this comparison because the variables has the same type.
return CurrentDT >= fDateParsed;
}).ToList();
I hope the code and my english is understandable,
if you need something else text to me.

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 remove date from datetime in Linq 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.

GetUtcOffset returns the wrong off set for certain years / dates

var currentServerOffset = TimeZone.CurrentTimeZone.GetUtcOffset(new DateTime(1972, 03, 19, 02, 00, 00);
using the above returns the wrong offset, but when you pass through 26th March it is corrected.
it seems that this is off for a whole week, in my tests this has been in 1972 and 1973 ref: https://greenwichmeantime.com/info/calendars/bst-dates/
I am thinking it could be something to do with GetDaylightChanges being wrong in these years ref: https://learn.microsoft.com/en-us/dotnet/api/system.timezone.getdaylightchanges?view=netframework-4.8#remarks
as when i call this passing in 1972 or 1973 the start is off by 7 days.
How do i get around this?
We couldn't get GetUtcOffset to work with historic dates. Instead we used Noda Time which should be as easy as:
var dt = Instant.FromUtc(1972, 03, 19, 02, 00, 00);
DateTimeZone zone = DateTimeZoneProviders.Tzdb["Europe/London"];
Offset offset = zone.GetUtcOffset(dt);

DateTime month 0 invalid format

I'm having strange behavior of DateTime in c#.
I'm trying to initialize a datepicker in January. So I make a new date:
DateTime MyDate = new DateTime(2017, 0, 15);
But I get this exception:
System.ArgumentOutOfRangeException: Year, Month, and Day parameters describe an un-representable DateTime.
If I use (2017, 1, 15) it works but the time dialog, initialized with:
DatePickerDialog dialog = new DatePickerDialog(
Activity,
this,
MyDate.Year,
MyDate.Month,
MyDate.Day);
Goes on February.
Well I tried to "cheat" and did:
DateTime MyDate = new DateTime(2017, 1, 15);
DateTime = DateTime.AddMonths(-1);
No error, but the date picker goes on February.
The only way to have January is:
DateTime MyDate = new DateTime(2017, 12, 15);
What am I doing wrong?
DateTime.Month is a value between 1 and 12, which aligns with what most people think a month 'number' is.
Per the android docs, theDatePickerDialog constructor you are calling accepts a zero-based month. It accepts values in the range 0-11, so you need to subtract one from the DateTime.Month.
DatePickerDialog dialog = new DatePickerDialog(Activity,
this, MyDate.Year, MyDate.Month - 1, MyDate.Day);
The issue is how the DateTime object treats month values (1-12) and how the DatePickerDialog treats month values (0-11).
DateTime constructor:
strange behavior of DateTime
DateTime MyDate = new DateTime(2017, 0, 15);
If we take a look at the DateTime constructor, it is clearly stated that the month value should be 1 through 12, which is not valid in your case and hence the exception. We can correct it as below:
DateTime MyDate = new DateTime(2017, 1, 15);
DatePickerDialog constructor:
Exception (or strange behavior) will arise when we try - new DatePickerDialog in combination with the month value of DateTime as the constructor of DatePickerDialog is expecting the month values from 0-11.
It is stated that int: the initially selected month (0-11 for compatibility with MONTH)
The approach which can then be followed is to give the correct index for month to DatePickerDialog constructor as below:
DateTime MyDate = new DateTime(2017, 1, 15);
DatePickerDialog dialog = new DatePickerDialog(Activity,
this,
MyDate.Year,
MyDate.Month - 1,
MyDate.Day);

DateTimeOffset proper usage

If I have a DateTime instance which represents a valid UTC time, and an offset that converts that DateTime to the time zone where it applies, how do I construct a DateTimeOffset instance to represent this?
var utcDateTime = new DateTime(2011, 02, 29, 12, 43, 0, /*DateTimeKind.Utc*/);
var localOffset = TimeSpan.FromHours(2.0);
var dto = ...
// Here the properties should be as follows;
// dto.UtcDateTime = 2011-02-29 12:43:00
// dto.LocalDateTime = 2011-02-29 14:43:00
Perhaps I'm not understanding the DateTimeOffset structure correctly, but I'm unable to get the expected output.
Thanks in advance
Looks like you want:
var utcDateTime = new DateTime(2012, 02, 29, 12, 43, 0, DateTimeKind.Utc);
var dto = new DateTimeOffset(utcDateTime).ToOffset(TimeSpan.FromHours(2));
Note that I changed the year from 2011 (which is not a leap year and does not have 29 days in February) to 2012.
Test:
Console.WriteLine("Utc = {0}, Original = {1}", dto.UtcDateTime, dto.DateTime);
Output:
Utc = 2/29/2012 12:43:00 PM, Original = 2/29/2012 2:43:00 PM
Do note that you probably don't want the LocalDateTime property, which may represent the instant in time as of the local system's timezone.

Categories

Resources