String was not recognized as a valid DateTime - Whats wrong? - c#

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)

Related

How to get the current date in DataTable.Compute

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.

MongoDB .NET Driver - Convert string to DateTime and for Filter Builder

var builder = Builders<ModelClass>.Filter;
var filter = builder.Where(x => x.Active);
if (fromDate.HasValue)
{
var date = fromDate.Value;
var subfilter = builder.Where(x => DateTime.Parse(x.EnrollmentDate) >= date);
filter &= subfilter;
}
Enrollment Date is saved as a string:
public string EnrollmentDate { get; set; }
, I need to filter docs within a set of date range, but how do I compare this? I need to filter like this.
I get
System.InvalidOperationException: Parse({document}{EnrollmentDate}) is not supported.
Error in subfilter line.
I think you need to achieve with MongoDB query as below:
{
"$expr": {
"$gte": [
{ "$toDate": "$EnrollmentDate" },
date
]
}
}
While I think it is not achievable with MongoDB .Net Driver LINQ syntax, you convert the query as BsonDocument:
var subfilter = new BsonDocument("$expr",
new BsonDocument("$gte",
new BsonArray {
new BsonDocument("$toDate", "$EnrollmentDate"),
date
}
)
);
filter &= subfilter;
You have problem here when you want to do DateTime.Parse()
Can you post format of your string EnrollmentDate? And your variable date , is it only Date or DateTime?
This one maybe can help you here
Also, try to use
var subfilter = builder.Gte(x=>x.Y, Z)

Search works on all fields except the date field

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.

How to resolve "String was not recognized as a valid DateTime"?

I'm converting a text field into date time and inserting into db. However, when the text field is null, it throws an exception that
String was not recognized as a valid DateTime
This is what I did:
nvpt4Entities db = new nvpt4Entities();
ClassInfo order = new ClassInfo
{
ClassID = classID.Text,
ClassName = className.SelectedItem.Text,
ClassTime = classTime1.Text,
ClassDate = DateTime.ParseExact(classDate1.Text, "MM/dd/yyyy", null),
ClassDay = classDay.SelectedValue,
ClassMonth = classMonth.SelectedValue,
ClassLocation = classLocation.SelectedItem.Text,
ClassNotes= classNotes.Text,
ClassInstructor = classInstructor.SelectedValue,
ClassInstructor1 = classInstructor2.SelectedValue,
ClassInstructor2 = classInstructor3.SelectedValue,
MultiDate2 = DateTime.ParseExact(multidate2.Text, "MM/dd/yyyy", null),
MultiDate3 = DateTime.ParseExact(multidate3.Text, "MM/dd/yyyy", null),
MultiDate4 = DateTime.ParseExact(multidate4.Text, "MM/dd/yyyy", null),
MultiDate5 = DateTime.ParseExact(multidate5.Text, "MM/dd/yyyy", null),
ClassStrength = Convert.ToInt16(classStrength.Text),
ClassProvider = classProvider.SelectedItem.Text,
LocationID = Convert.ToInt16(classLocation.SelectedValue),
ClassCID = Convert.ToInt16(className.SelectedValue),
ProviderID = Convert.ToInt16(classProvider.SelectedValue)
};
So, I want to know how to handle null strings to be converted to datetime while inserting into db
This has nothing to do with the database. Pay attention to the error message and where the exception originates. The only thing of relevance is where the error comes from:
DateTime.ParseExact(__, "MM/dd/yyyy", null)
Replace this with an appropriate method call that handles the "empty/invalid string" case, however is appropriate, or use validation to ensure this step is never reached; DateTime? should be used for nullable columns, a sentinel can be used otherwise. (See Mark Byers' answer for what the contents of said method may look like.)
Happy coding.
If your fields are nullable DateTimes you can use this:
ClassDate = string.IsNullOrEmpty(classDate1.Text) ? (DateTime?)null :
DateTime.ParseExact(classDate1.Text, "MM/dd/yyyy", null),

How to query with the datetime value using LINQ to XML?

I am developing window phone 7 application in silverlight. I am new to the silverlight. I am also new to LINQ to XML. In my application the user select the date & submit some transaction details into the application. The details gets stored in XML File. I am using the custom date control in my application for the date selection as follows
private void DatePicker_ValueChanged(object sender, DateTimeValueChangedEventArgs e)
{
AppObj = Application.Current as App;
AppObj.date = (DateTime)EntryDate.Value;
}
Then the value of AppObj.date gets stored in the XML file. Sometimes I use the DateTime.Now to store the date in the XML File. Now I want to generate the report of submitted transaction details by querying through LINQ to XML. I want to generate the report for today's date, current week & current month. For today's date report I am using the following code
public void GetTransactionObjects(String strXMLFile, DateTime VDateTime)
{
XDocument doc = null;
XMLFileManager XMLDocObj = new XMLFileManager();
doc = XMLDocObj.LoadXMLFile(strXMLFile);
var vTransaction = from s in doc.Descendants("Transaction")
.Where(x => x.Element("Current_Date").Value == VDateTime.ToShortDateString())
select new Transaction(s);
this.Clear();
AddRange(vTransaction);
}
The Transaction class contains the following constructor.
public Transaction(XElement xElement)
{
Transaction_ID = Convert.ToInt32(xElement.Element("Transaction_ID").Value.ToString());
TransactionType_ID = Convert.ToInt32(xElement.Element("TransactionType_ID").Value.ToString());
Alphabet_ID = Convert.ToInt32(xElement.Element("Alphabet_ID").Value.ToString());
ID = Convert.ToInt32(xElement.Element("ID").Value.ToString());
SubCategory_ID = Convert.ToInt32(xElement.Element("SubCategory_ID").Value.ToString());
Item_ID = Convert.ToInt32(xElement.Element("Item_ID").Value.ToString());
Currency_ID = Convert.ToInt32(xElement.Element("Currency_ID").Value.ToString());
InputTypeMethod_ID = Convert.ToInt32(xElement.Element("InputTypeMethod_ID").Value.ToString());
Principle = Convert.ToInt32(xElement.Element("InputTypeMethod_ID").Value.ToString());
Interest = Convert.ToInt32(xElement.Element("Interest").Value.ToString());
ROI = Convert.ToInt32(xElement.Element("InputTypeMethod_ID").Value.ToString());
Amount = Convert.ToInt32(xElement.Element("InputTypeMethod_ID").Value.ToString());
Current_Date = Convert.ToDateTime(xElement.Element("Current_Date").Value.ToString());
}
In the XML File the value gets stored for date & time. The value gets stored as follows
<Transactions>
<Transaction>
<Transaction_ID>0</Transaction_ID>
<TransactionType_ID>0</TransactionType_ID>
<Alphabet_ID>3</Alphabet_ID>
<ID>0</ID>
<SubCategory_ID>0</SubCategory_ID>
<Item_ID>0</Item_ID>
<Currency_ID>3</Currency_ID>
<InputTypeMethod_ID>0</InputTypeMethod_ID>
<Principle>0</Principle>
<Interest>0</Interest>
<ROI>0</ROI>
<Amount>5000</Amount>
<Current_Date>2010-12-31T18:08:23.433+05:30</Current_Date>
</Transaction>
</Transactions>
Look at the node
<Current_Date>2010-12-31T18:08:23.433+05:30</Current_Date>
The date format is yyyy-mm-dd.
Now how should I write the following query to get all the submitted transaction details for today's date ?
var vTransaction = from s in doc.Descendants("Transaction")
.Where(x => x.Element("Current_Date").Value == VDateTime.ToShortDateString())
select new Transaction(s);
Similarly how should I write the query to get all the transaction details for the current week & current month? Can you please provide me any code or link through which I can resolve the above issue ? If I am doing anything wrong then please guide me.
Don't use Convert.ToDateTime or ToShortDateString etc with LINQ to XML. Use the conversions which already exist in XAttribute and XElement. For example:
DateTime today = DateTime.Today;
var query = doc.Descendants("Transaction")
.Where(x => ((DateTime) x.Element("Current_Date")).Date == today)
.Select(x => new Transaction(s));
(You should use the conversion operator in your Transaction constructor too.)

Categories