I have a search function which includes dates also. The problem that i have is this:
when you add 2 dates in the search function for example:
2013-04-10 and 2013-04-11 it displays just for 2013-04-10 until 23:59 or if i search the same date
2013-04-10 and 2013-04-10 it doesn't find any hit.
the code is this:
Func<string, string> emptyToNull = s => String.IsNullOrWhiteSpace(s) ? null : s.Trim();
var from = emptyToNull(input.CreditApplicationSearchFromDate);
var to = emptyToNull(input.CreditApplicationSearchToDate);
from = from ?? DateTime.Today.ToString("yyyy-MM-dd");
to = to ?? DateTime.Today.ToString("yyyy-MM-dd");
And i was thinking to do like this:
Func<string, string> emptyToNull = s => String.IsNullOrWhiteSpace(s) ? null : s.Trim();
var from = emptyToNull(input.CreditApplicationSearchFromDate);
var to = emptyToNull(input.CreditApplicationSearchToDate);
from = from ?? new DateTime().ToString("yyyy-MM-dd HH:mm");
to = to ?? new DateTime().ToString("yyyy-MM-dd HH:mm");
but is not good and i don't know how to do to display when i search for example
2013-04-10 and 2013-04-10 to find the hits for all day
You need to specify the start and end hours of the whole day, or better yet - the very start of the next day:
from = from ?? DateTime.Now.Date.ToString("yyyy-MM-dd");
to = to ?? new DateTime.Now.Date.AddDays(1).ToString("yyyy-MM-dd");
Note the use of Now.Date giving you the current date without a time component (new DateTime() will not compile, so I don't really know where you got that piece of code from).
Related
I am trying to compute the string expression by DataTable.Compute.
A simple string like below is working:
static void Compare()
{
var logicalExpression = "'2022-09-14' <= '2029-12-31'";
DataTable dt = new DataTable();
var result = (bool)dt.Compute(logicalExpression, "");
}
But, the date 2022-09-14 is dynamic, it should be the date for now.
I have tried to replace '2022-09-14' with Now(),GETDATE(). None of them work.
Is there any function to get current date time in Compute?
You can do this like this:
var logicalExpression = "'" + DateTime.Now.ToShortDateString() + "' <= '2029-12-31'";
you can also specify in what format you want the date, see this post for an example.
var logicalExpression = $"#{DateTime.Now:MM/dd/yyyy}# <= #12/31/2029#";
This is the proper way to represent dates in this context. See here for more information.
I am a real newbie in C#, and I am trying to get the most recent modification time (LastWriteTime) for any file in a directory.
What is a simple way to get this information ?
I would simplify your code to use this approach:
DirectoryInfo di_source_directory = new DirectoryInfo(#"C:\MyFolder");
FileSystemInfo[] ls_fi = di_source_directory.GetFileSystemInfos();
DateTime ts_most_recent = (ls_fi.Any()
? ls_fi.Max(fi => fi.LastWriteTime)
: default(DateTime));
or just replace the default(DateTime) part with new DateTime(.....)
I could retrieve the timestamp of the most recent updated file using this code, with the help of #DiplomacyNotWar:
DirectoryInfo di_source_directory = new DirectoryInfo(#"C:\MyFolder");
FileSystemInfo[] ls_fi = di_source_directory.GetFileSystemInfos();
DateTime defaultTS = new DateTime(2022, 1, 1);
DateTime ts_most_recent = ls_fi.Select(fi => fi.LastWriteTime).DefaultIfEmpty(defaultTS).Max();
I'd like to search data by date with format (dd/MM/yyyy) for example "20/01/2021". the search works on ADDRESS and NAME fields but not on the CREATE_DATE.
This is my code :
// search
if (!string.IsNullOrEmpty(search))
{
List<string> terms = search.Split(',').ToList().ConvertAll(d => d.ToLower());
res = res.Where(x =>
terms.Any(
str => x.NAME.Contains(str) ||
x.ADDRESS.Contains(str) ||
x.DATE_CREATE.ToString().Contains(str)
));
var test = res.FirstOrDefault().DATE_CREATE.ToString();
}
This is the request :
http://localhost:6289/api/Customer?search=20/01/2021,hous
and this is the outputs of terms and test var :
and this is how the dates are saved , they dates are with datetime type
Your code actually works on my machine BUT only in case I use appropriate culture settings as #JustShadow pointed out.
Appropriate culture: which results a datetime.ToString() formating date in dd/MM/yyyy format.
For test purpose I used "es-ES" culture for example with the following code inside your if statement:
Thread.CurrentThread.CurrentCulture = new CultureInfo("es-ES");
I suggest modifying your code according to this:
if (!string.IsNullOrEmpty(search))
{
List<string> terms = search.Split(',').ToList().ConvertAll(d => d.ToLower());
var originalCulture = Thread.CurrentThread.CurrentCulture;
try
{
// use any locale which results a datetime.ToString() output in dd/MM/yyyy format
Thread.CurrentThread.CurrentCulture = new CultureInfo("es-ES"); ;
res = res.Where(x =>
terms.Any(
str => x.NAME.Contains(str) ||
x.ADDRESS.Contains(str) ||
x.DATE_CREATE.ToString().Contains(str)));
var test = res.FirstOrDefault().DATE_CREATE.ToString();
}
finally
{
Thread.CurrentThread.CurrentCulture = originalCulture;
}
}
This will be enough if your input will have always dd/MM/yyyy format.
Edit:
You can try to use custom format string in ToString() call to achieve a working code as #bitapinches suggests. I think my solution performs better because there is no need to parse the custom format string in each comparison LINQ will execute. Here is the alternative for reference:
if (!string.IsNullOrEmpty(search))
{
List<string> terms = search.Split(',').ToList().ConvertAll(d => d.ToLower());
res = res.Where(x =>
terms.Any(
str => x.NAME.Contains(str) ||
x.ADDRESS.Contains(str) ||
x.DATE_CREATE.ToString(#"dd\/MM\/yyyy").Contains(str)));
var test = res.FirstOrDefault().DATE_CREATE.ToString();
}
I think cast datatime to date ToString() you need to convert date format like "dd/MM/yyyy" which is the parameter (search=20/01/2021) in your url then Here [x.DATE_CREATE.ToString().Contains(str)] i would use "equals" be like [x.DATE_CREATE.ToString("dd/MM/yyyy").equals(str)] to be more specific on the query.
I have the following model with two properties (End and Final).
I'm trying to set my "Final" property value with the the day and month of my "End" property value as such as the example bellow:
I'm just not sure how to accomplish this... Any feedback would be greatly appreciated so that I could return my NewModel with the correct value.
Example:
End = 2/3/2008
Final = 1/1/2019 but I would like the value to be set as such 2/3/2019
Maybe my answer would be to create a new properties that add the value of both property?
var newModel = new ProgramSchedule(customerProgram.RepeatBy)
{
End = !customerProgram.EndOn.HasValue ? (customerProgram.IsNonServiceYear ?
DateTime.Today.AddYears(1) : new DateTime((customerProgram.Year ?? DateTime.Today.Year), 12, 31)) :
customerProgram.EndOn.Value,
Final = GetServiceYearWithDefault(),};
return newModel;}
public DateTime GetServiceYearWithDefault()
{
int defaultYear =((short?)Parameters.ParameterConfigurationService.GetParameterValue(ParameterConfiguration.GeneralParameterKeys.Year)) ?? (int)DateTime.Now.Year;
DateTime Final = new DateTime(defaultYear, DateTime.Now.Month, DateTime.Now.Day);
return Final;
}
I have been getting an annoying littler error and cannot for the life of me figure out why it is being cause. I have an xml file where i am storing data, as shown below.
- <EmployeeFinance>
<EmployeeEmploy_Id>5584</EmployeeEmploy_Id>
<EmpPersonal_Id>30358</EmpPersonal_Id>
<No_DaysWorked>30</No_DaysWorked>
<Date_Appointment>17/02/2012</Date_Appointment>
<Date_Employment>02/05/1984</Date_Employment>
<Date_Termination>01/01/0001</Date_Termination>
<Payperiod_StartDate>01/01/2013</Payperiod_StartDate>
<Payperiod_EndDate>31/01/2013</Payperiod_EndDate>
<BatchNumber>38</BatchNumber>
<PAYE_ToDate_Computed>0</PAYE_ToDate_Computed>
<Income_Tax_RateID>0</Income_Tax_RateID>
<NIS_RateID>0</NIS_RateID>
<NIS_weeks_worked>0</NIS_weeks_worked>
</EmployeeFinance>
If you look at the date nodes, Payperiod_StartDate,Payperiod_EndDate, Date_Appointment etc. They all have the same format. Now in my C# code, when i write my query to select from the xml file i get the String was not recognized as a valid DateTime error. WHen i comment out all the other dates and leave start_date, it works. They are the same format , i cant see what i am doing wrong. Please help me.
var context = new SSPModel.sspEntities();
XElement xelement = XElement.Load(GlobalClass.GlobalUrl);
XDocument doc = XDocument.Load(GlobalClass.GlobalUrl);
var query = from nm in xelement.Elements("EmployeeFinance")
select new EmployeeEmploy
{
Employee_Personal_InfoEmp_id = (int)nm.Element("EmpPersonal_Id"),
Substantive_designation = (int)nm.Element("Position_Id"),
Grade_Id = (int)nm.Element("Grade_Id"),
PositionTotal_PtBasic = (double)nm.Element("Sum_AllPosition"),//part of basic
GradeTotal_PtBasic = (double)nm.Element("Sum_AllGrade"), //part of basic
Housing_Allowance = (double)nm.Element("Housing"),
Base_Pay = (double)nm.Element("Base_Pay"),
startDate = (DateTime)nm.Element("Payperiod_StartDate"),
endDate = (DateTime)nm.Element("Payperiod_EndDate"),
Date_of_Appointment = (DateTime)nm.Element("Date_Appointment"),
Date_of_Employment = (DateTime)nm.Element("Date_Employment"),
Termination_date_actual = (DateTime)nm.Element("Date_Termination"),
Base_Pay_Currency = (string)nm.Element("Currency"),
Exchange_rate = (double)nm.Element("Exchange_Rate")
};
var x = query.ToList();
foreach (var xy in x) {
Debug.WriteLine(xy.endDate);
}
Because 17/02/2012 is not a valid date, however, 02/17/2012 is. The date will be parsed as mm/dd/yyyy. One option is to use DateTime.ParseExact to parse a date with the dd as the first set of numbers. e.g.
var startDate = DateTime.ParseExact("17/02/2012", "dd/MM/yyyy", null);
The debugger will show you that nm.Element("Payperiod_EndDate").ToString() gives you a string that includes the xml tags for that element. Try the following instead:
startDate = DateTime.ParseExact(nm.Element("Payperiod_EndDate").Value, "dd/MM/yyyy", null)