How do I compare datetime with value from datepicker? - c#

I need to compare the chosen date with the date in a database and return values within the date range but keep getting incorrect format. The date format in the database is 2016-01-02 00:00:00.000 (from one of the rows)
I am using the code below but am unable to compare and keep getting"String was not recognized as a valid DateTime." Help?
protected void RadPushButton1_Click(object sender, EventArgs e)
{
DateTime startDate = DateTime.Parse(RadDatePickerStart.SelectedDate.ToString());
string s = startDate.Date.ToString("yyyy-dd-MM");
startDate = DateTime.Parse(s+"12:00:00 AM");
// DateTime endDate = DateTime.Parse(RadDatePickerEnd.SelectedDate.ToString());
EMCSettlementManager man = new EMCSettlementManager();
Grid.DataSource = man.GetSTL010(r => EntityFunctions.TruncateTime( r.settlement_date) >= startDate);
Grid.DataBind();
}

If you want to compare dates, make sure all values are of type DateTime, not String.
Try something like this:
DateTime startDate = RadDatePickerStart.SelectedDate;
EMCSettlementManager man = new EMCSettlementManager();
Grid.DataSource = man.GetSTL010(r => r.settlement_date >= startDate);
If you want to get rid of the time-part, you could do something like this:
DateTime startDate = RadDatePickerStart.SelectedDate.Date;
If the field in the database is a string-type, not a datetime, please convert it to a Date(Time)-type. Using strings everywhere is a bad choise, alsnog known as 'stringly typed'. (See: https://blog.codinghorror.com/new-programming-jargon/)

Related

Retrieve a string from database and compare with date

I have a field in database stored as string and i need to convert it back to datetime and then compare if it equals to date. Below is the current implementation I have presently.
var date = DateTime.UtcNow ;
var zone = TimeZoneInfo.FindSystemTimeZoneById("W. Central Africa Standard Time");
DateTime currentTime = TimeZoneInfo.ConvertTimeFromUtc(date, zone);
var loanDate = currentTime.Date.ToString("dd/MM/yyyy").Replace("-", "/");
if (DateTime.ParseExact(firstRepay, "dd/MM/yyyy", CultureInfo.InvariantCulture).Date.ToString("dd/MM/yyyy").Replace("-", "/") == WATTime.Date.ToString("dd/MM/yyyy").Replace("-", "/"))
{ // Do this
}
note that the firstRepay is in the format 06/02/2021 in the database but it might be 06-02/2021 depending on server format.
Assuming loanDate and dbDate are in the same format "dd/MM/yyyy" and the dbDate also can be in "dd-MM/yyyy" format, you can try this code
var dateFromDb="01-02/2021"; // 1 Feb 2021
var loanDate="06/02/2020"; // 6 Feb 2020
var dbDate = dateFromDb.Replace("-", "/");
var dbDateTime = DateTime.ParseExact(dbDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
var loanDateTime= DateTime.ParseExact(loanDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
var diffDateDays=(dbDateTime-loanDateTime).Days; // = 361
//or you can use it this way:
if ((dbDateTime-loanDateTime).Days > 0) //.... then
If dates are in a different string format you just have to change string
"dd/MM/yyyy" to "MM/dd/yyyy" for example for this date, but the algorithm will be still the same.
Please try to use like below.
string dateString = "21-Jan-2021";
DateTime otherDate=new DateTime(2021,3,3);
// Convert a null string.
DateTime mydateTime;
if(DateTime.TryParse(dateString, out mydateTime))
{
//dateString is converted to DateTime in mydateTime
if(mydateTime==otherDate)//Check with exact Date and time
{
//DB date and other date is equal
}
if(mydateTime.Date==otherDate.Date)//Check with Only date
{
//DB date and other date is equal
}
}
Note: Learn different way to convert string to DateTime How to Convert String To DateTime in C#.
Which database you are using, you should directly parse date in your SQL query.
Below is sample for SQL Server
SELECT CAST('06/02/2021' as date) as MyDate
SELECT CAST(REPLACE('06-02/2021','-','/') as date) as MyDate
SELECT CAST(REPLACE('06-02-2021','-','/') as date) as MyDate
SELECT CAST(REPLACE('06-February-2021','-','/') as date) as MyDate
All these will return date which will be directly casted as DateTime in C#. You can parse all your rows using SQL statement at once.
If you have space or some extra chars that can be managed by trim/ regex.

Get data day from date when selecting datagridview row

i have dgvData(datagridview), cmbPickRoom(combobox), numDay_In & numDay_Out(numericupdown) and code which like this
private void dgvData_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
DataGridViewRow row = this.dgvData.Rows[e.RowIndex];
cmbPickRoom.Text = row.Cells["Room"].Value.ToString();
numDay_In.Text = row.Cells["Day_In"].Value.ToString();
numDay_Out.Text = row.Cells["Day_Out"].Value.ToString();
}
}
while the data in mysql store date format(dd-mm-yyyy) for both "Day_In" and "Day_Out".
I want when i click dgvData, numDay_In and numDay_Out only take the day(dd)
If the database fields are of type DateTime, (Day_In and Day_Out) then you don't need to convert these values to string but to a DateTime variable, then getting the day is just a matter of reading a property
DateTime inDate = Convert.ToDateTime(row.Cells["Day_In"].Value);
numDay_In.Text = inDate.Day.ToString();
You can use DateTime.TryParse to convert the user entered string to date time format and then get the Day from it as I have done in the below code.
DateTime dt = new DateTime();
if(DateTime.TryParse(row.Cells["Day_In"].Value, out dt))
{
numDay_In.Text = dt.Day.ToString();
}
else
{
//Code to display error message
}
The added advantage of this code is that you can check if the user entered format is coorect, by checking the success of the TryParse in an if condition, If it fails, you can prompt the user to enter the Date in the correct format.

How to get dates between two dates in C#

I would like to get dates between two dates. Instead of expected 9 different dates, I get 875287 and run out of memory. What would be the problem with the code below?
StartDate value is 01/04/2016 00:00:00
EndDate value is 10/04/2016 00:00:00
var selectedDates = new List<DateTime?>();
for (var date = StartDate; date <= EndDate; date.Value.AddDays(1))
{
selectedDates.Add(date);
}
You aren't assigning the value of date.Value.AddDays(1) to anything, so it ends up in an infinite loop. You'd need to change your code so that date is set to the result of AddDays.
for (var date = StartDate; date <= EndDate; date = date.AddDays(1))
{
selectedDates.Add(date);
}
LINQ solution (let's generate selectedDates):
var selectedDates = Enumerable
.Range(0, int.MaxValue)
.Select(index => new DateTime?(StartDate.AddDays(index)))
.TakeWhile(date => date <= EndDate)
.ToList();
As far as I can see, since AddDays method returns a new instance of a DateTime, it does not change the current instance since DateTime is immutable.
Looks like your date is DateTime?, you can change this part as;
for (var date = StartDate; date <= EndDate; date = date.Value.AddDays(1))
{
selectedDates.Add(date);
}
As usr pointed, this might be affected on DST. You might wanna check Dmitry's answer as well.
A shorter notation using Linq's Range method uses the ability to already figure out the number of days using the TimeSpan.Days property after subtracting start from end.
Assuming the start is before end you'd end up with:
DateTime StartDate = new DateTime(1979, 10, 4);
DateTime EndDate = new DateTime(2016, 10, 4);
var dates = Enumerable.Range(0, (EndDate - StartDate).Days + 1)
.Select(day => StartDate.AddDays(day))
If you need it to be Nullable, add:
.Cast<DateTime?>()
If you need this to be a List, add:
.ToList()
It's probably quite a bit more efficient than the other LINQ based solution.
Decided to change it up with a do/while
var selectedDates = new List<DateTime?>();
DateTime? StartDate = DateTime.Parse("01/04/2016 00:00:00");
DateTime? EndDate = DateTime.Parse("10/04/2016 00:00:00");
do
{
selectedDates.Add(StartDate);
StartDate = StartDate.Value.AddDays(1);
}while(StartDate < EndDate);

Storing dates in a list using c#

I have two textboxes and a button, both textbox have calender attach to them. I want to store the dates which are between the first textbox and second textbox in a list, I am invoking following method on button click.
private void CollectDates()
{
DateTime StartDate = Convert.ToDateTime(txtFromDate.Text);
DateTime EndDate = Convert.ToDateTime(txtTillDate.Text);
List<DateTime> datelist = new List<DateTime>();
for (StartDate = Convert.ToDateTime(txtFromDate.Text); StartDate < Convert.ToDateTime(txtTillDate.Text); StartDate.AddDays(1))
{
datelist.Add(StartDate);
}
}
But I am getting error after storing the first date in the list: Exception of type 'System.OutOfMemoryException' was thrown.
I think my loop is running endlessly, any help will be appreciated.
DateTime.AddDays() does not change the datetime you must assign its return value. Like
StartDate = StartDate.AddDays(1)
It is indeed an infinite loop. You're stating that if the start date is less than the end date, add start date to the list. It'll keep doing this for infinity as start date should always (in theory) be less than the end date. The add days function isn't assigned to a variable so it never gets added to the start date.
Also another piece of advice with .Net datetime is to use the in-built compare function.
DateTime Compare function
Hope that helps!
Try this:
private void CollectDates()
{
DateTime StartDate = Convert.ToDateTime(txtFromDate.Text);
DateTime EndDate = Convert.ToDateTime(txtTillDate.Text);
List<DateTime> dateList = new List<DateTime>();
DateTime currentDate = StartDate;
while(currentDate <= EndDate)
{
dateList.Add(currentDate);
currentDate.AddDays(1);
}
}
use this
for (int i =0; i<(EndDate-StartDate).Days; i++)
{
datelist.Add(StartDate.AddDays(i));
}
you might want to try linq:
Enumerable.Range(0, (int)endDate.Subtract(startDate).TotalDays)
.Select(d => startDate.AddDays(d))
.ToList()

Prevent user from entering a from date greater than to date c#

I am searching data based on two dates a from field and a To field in Asp.net
I want to prevent the user from entering a From date greater than a To date and display a message to the user Please select a valid date range
DateTime InvoiceDateFrom = new DateTime();
DateTime InvoiceDateTo = new DateTime();
if (TxtInvoiceDateFrom.Text.Trim() != "")
{
//DateTime FromDate = DateTime.ParseExact(TxtInvoiceDateFrom.Text.Trim(), "dd/MM/yyyy", null).AddDays(1);
InvoiceDateFrom = Convert.ToDateTime(TxtInvoiceDateFrom.Text);
//DateTime toDate = DateTime.ParseExact(TxtInvoiceDateTo.Text.Trim(), "dd/MM/yyyy", null).AddDays(1);
}
if (TxtInvoiceDateTo.Text.Trim() != "")
{
InvoiceDateTo = Convert.ToDateTime(TxtInvoiceDateTo.Text);
}
if (InvoiceDateTo < InvoiceDateFrom)
MessageBox.Show("Please select a valid date range.");
DateTime x = DateTime.Parse("12/8/2012"); //as "12/8/2012" is the your specified date
dateTimePicker1.MaxDate = x; // or you can use it in one line
if you want to prevent the user to choose date greater than today:
dateTimePicker1.MaxDate = DateTime.Today;
Please see if this is of help! C# way of doing is fine. But i would rather suggest javascript.
DateTime toDate=DateTime.ParseExact(todateString,"dd/MM/yy",System.Globalization.InvariantCulture);
DateTime fromDate=DateTime.ParseExact(fromdateString,"dd/MM/yy",System.Globalization.InvariantCulture);
int comparison=DateTime.Compare(toDate,fromDate);
if(comparison>=0)
{
//Post custom error message.
}

Categories