This question already has answers here:
DBNull if statement
(12 answers)
Closed 7 years ago.
I am writing an web application. I want to check if the dateFrom is null or if dateTo is null. If dateFrom is null, print out dateTo, if dateTo is null, then print out dateFrom. If both of then exist, then print out the formation such as 12/3/2015 - 12/3/2015. I have most of the code working, but I cannot figureout how to handle the null date. It keep giving me this exception
String was not recognized as a valid DateTime
Here is my code
public DataSet SearchTimingReq()
{
DateTime effectDateFrom, effectDateTo;
DataSet ds = someDataSet();
if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{
foreach (DataRow row in ds.Tables[0].Rows)
{
if (Convert.ToDateTime(row["Effect_Date_To"].ToString()).ToString("dd/MM/yyyy") == DateTime.MinValue.ToString())
{
row["Effective_Period"] = effectDateFrom.ToString("dd/MM/yyyy");
}
if (Convert.ToDateTime(row["Effect_Date_From"].ToString()).ToString("dd/MM/yyyy") == DateTime.MinValue.ToString())
{
row["Effective_Period"] = effectDateTo.ToString("dd/MM/yyyy");
}
if (effectDateTo != DateTime.MinValue && effectDateFrom == DateTime.MinValue)
{
row["Effective_Period"] = Convert.ToDateTime(row["Effect_Date_From"].ToString()).ToString("dd/MM/yyyy") + " - " + Convert.ToDateTime(row["Effect_Date_To"].ToString()).ToString("dd/MM/yyyy");
}
}
}
}
Updated code
if (!DBNull.Value.Equals(row["Effect_Date_From"]))
{
row["Effective_Period"] = Convert.ToDateTime(row["Effect_Date_To"].ToString()).ToString("dd/MM/yyyy");
}
if (!DBNull.Value.Equals(row["Effect_Date_To"]))
{
row["Effective_Period"] = Convert.ToDateTime(row["Effect_Date_From"]).ToString("dd/MM/yyyy");
}
if (DBNull.Value.Equals(row["Effect_Date_To"]) && DBNull.Value.Equals(row["Effect_Date_From"]))
{
row["Effective_Period"] = Convert.ToDateTime(row["Effect_Date_From"].ToString()).ToString("dd/MM/yyyy") + " - " + Convert.ToDateTime(row["Effect_Date_To"].ToString()).ToString("dd/MM/yyyy");
}
You can use the code below to check for null values on a datatable's datarows.
if (DBNull.Value.Equals(row["Effect_Date_From"]))
{
// null
}
You can use DateTime.TryParse to handle invalid DateTime values and also parse the date at the same time.
DateTime d;
if(DateTime.TryParse(row["column"], out d))
{
//it's a valid DT
}
else
{
//invalid
}
Related
This question already has answers here:
Linq Overlapped date range checking in single collection
(2 answers)
Closed 1 year ago.
I have a datatable having startdate and enddate columns. I want to check overlapping startdate and enddate using linq.
method input Parameters:
Input DataTable
startDate
endDate
01/Jan/2021
31/Jan/2021
01/Feb/2021
28/Feb/2021
Input Parameters
FromDate: 15/Feb/2021
ToDate: 20/Feb/2021
Expected OutPut: true
I have created a function to check for overlapping dates.
private bool IsDateOverlap(DateTime? FromDate, DateTime? ToDate, DataTable Table)
{
bool isOverlap = false;
try
{
for (int index = 0; index < Table.Rows.Count; index++)
{
if (index == this.RowID)
continue;
DateTime? rowFromDate = Convert.ToDateTime(Table.Rows[index]["startDate"]);
DateTime? rowToDate = Convert.ToDateTime(Table.Rows[index]["endDate"]);
isOverlap = (FromDate <= rowToDate && rowFromDate <= ToDate);
if (isOverlap)
break;
}
}
catch (Exception ex)
{ }
return isOverlap;
}
Its working fine.
I want to do it using linq. Thanks in Advance.
I have an approach that might help you how ever i use a custom object rather than a datatable.
public static List<inputDataTable> ListOfDates = new List<inputDataTable>
{
new inputDataTable { startDate = DateTime.Parse("01/Jan/2021"), endDate = DateTime.Parse("31/Jan/2021"),},
new inputDataTable { startDate = DateTime.Parse("01/Feb/2021"), endDate = DateTime.Parse("28/Feb/2021"),},
};
public static bool checkOverlapping(DateTime starDate, DateTime endDate, List<inputDataTable> storeDate)
{
var e = storeDate.Where(a=> (starDate >= a.startDate && starDate <= a.endDate) || (endDate >= a.startDate && starDate <= a.endDate) );
if(e.Count() > 0)
{
return true;
}
else
{
return false;
}
}
Also you can visit these threads;
Check dates fall within range using Linq
Check One Date is falling Between Date Range-Linq query
I have a list like below :
2016-10-05 00:00:00.000
NULL
NULL
NULL
2016-08-12 07:46:00.000
NULL
NULL
Which I need to convert to
2016-10-05 00:00:00.000
2016-10-05 00:00:00.000
2016-10-05 00:00:00.000
2016-10-05 00:00:00.000
2016-08-12 07:46:00.000
2016-08-12 07:46:00.000
2016-08-12 07:46:00.000
Basically, I need to capture the last occurrence date and copy it to next rows till i see a filled row.
Here is how I see it working now
foreach (var date in dates)
{
var lastValue = null;
if(date != null)
{
lastValue = date;
}
if(date == null)
{
date = lastValue;
}
else
{
lastValue = date;
}
}
I would use a simple for-loop for this
List<DateTime?> dates = new List<DateTime?>()
{
new DateTime( 2016,10,05,00,00,00),
null,
null,
null,
new DateTime( 2016, 08, 12 ,07,46,00),
null,
null
};
DateTime? latest = null;
for (int i = 0; i < dates.Count; i++)
{
if (dates[i].HasValue)
{
latest = dates[i];
}
else
{
dates[i] = latest;
}
}
https://dotnetfiddle.net/qqDaMf
//input
List<DateTime?> dates = new List<DateTime?> { DateTime.Now, null, DateTime.Parse("2019-10-01"), null };
DateTime? lastPresentDate = dates.FirstOrDefault();
if (lastPresentDate.HasValue)
{
dates = dates.Select(d => d.HasValue ? lastPresentDate = d : lastPresentDate).ToList();
}
//output
7/23/2019 7:15:48 AM
7/23/2019 7:15:48 AM
10/1/2019 12:00:00 AM
10/1/2019 12:00:00 AM
This will only correct the dates if the first date is present and otherwise leave the list as is.
Assuming you actually have a class (let's say Product) with some other properties:
DateTime? lastDate = null;
var result = products.Select(
p =>
new {
Id = p.Id,
CreateDate = (p.CreateDate.HasValue ? (lastDate = p.CreateDate) : lastDate)
//Other properties..
}
);
If not and you have just the dates:
DateTime? lastDate = null;
var result = dates.Select(d => (d.HasValue ? (lastDate = d.Value) : lastDate));
You can add .ToList() if you like or not.
Change String class for whatever class u are using.
String lastValue = null;
foreach(var value in ValuesList){
if(value == null)
value = lastValue;
else
lastValue = value;
}
Hei. I need to understand why I receive an error like that :
C# windows form import from excel error
I can't separe the year from string (year time). Or, can I renounce at split and import directly the string as "date"? Sorry, I'm too beginner in c#, but I need this help, is a task for me.
Here is my code :
for (int i = 0; i < dvColumns.Count; i++)
{
string columnName = string.Empty;
string columnField = string.Empty;
if ((dvColumns[i]["Header"] != null) && (!Convert.IsDBNull(dvColumns[i]["Header"])))
{
columnName = dvColumns[i]["Header"].ToString();
}
if ((dvColumns[i]["Field"] != null) && (!Convert.IsDBNull(dvColumns[i]["Field"])))
{
columnField = dvColumns[i]["Field"].ToString();
}
rangeObject = cellsObject.GetType().InvokeMember("Item", BindingFlags.GetProperty, null, cellsObject, new object[] { row, i + 1 });
object valueObject = rangeObject.GetType().InvokeMember("Value", BindingFlags.GetProperty, null, rangeObject, null);
if (columnName == "FiscalCode" && columnField == "PartnerId")
{
string fiscalCode = Erp.Core.Utils.GetStringFromObject(valueObject);
partnerId = p.GetPartnerIdByFiscalCode(fiscalCode);
eventRow["PartnerId"] = partnerId;
}
else if (columnField == "StartDate" || columnField == "EndDate")
{
string date = Erp.Core.Utils.GetStringFromObject(valueObject);
DateTime columnDate = DateTime.Now;
string[] dateComponents = null;
int year = 0;
int month = 0;
int day = 0;
if (date.Contains("."))
{
dateComponents = date.Split('.');
}
if (date.Contains("/"))
{
dateComponents = date.Split('/');
}
if (date.Contains(":"))
{
dateComponents = date.Split(':');
}
if (dateComponents.Length > 1)
{
string s = dateComponents[0];
day = Erp.Core.Utils.GetIntFromObject(s);
s = dateComponents[1];
month = Erp.Core.Utils.GetIntFromObject(s);
s = dateComponents[2];
year = Erp.Core.Utils.GetIntFromObject(s);
columnDate = new DateTime(year, month, day, 9, 0, 0);
}
eventRow[columnField] = columnDate;
}
else if (columnField != "PartnerId" && columnField != "StartDate" && columnField != "EndDate")
{
eventRow[columnField] = valueObject;
}
}
I tried to keep in excel same format as in database table : 'yyyy/mm/dd hh:mm:ss.000'.
The line date = Erp.Core.Utils.GetStringFromObject(valueObject); get my date from first excel cell.
ds.Tables["Events"] is all time empty.
I know this line eventRow[columnField] = date; must add the dates in DB, really? After split, day is ok (receive an int by s[0]), month is ok (receive an int by s[1], but s[2] for year is something like 2017 19:06:22 .... year plus time). I tried to split again by space, but without results, to keep the number (2017) in year variable.
Best way is to use DateTime.ParseExact method. In your case, if original format is 'yyyy/mm/dd hh:mm:ss.000', you can convert it to DateTime like this:
//string date = Erp.Core.Utils.GetStringFromObject(valueObject);
string date = "2017/08/15 10:20:30.000";
DateTime columnDate = DateTime.ParseExact(date, "yyyy/MM/dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
This way you can skip parsing excel string.
In your example, usage will be like this:
//...snip...
else if (columnField == "StartDate" || columnField == "EndDate")
{
string date = Erp.Core.Utils.GetStringFromObject(valueObject);
//parsing date string
DateTime columnDate = DateTime.ParseExact(date, "yyyy/MM/dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
eventRow[columnField] = columnDate;
}
else if (columnField != "PartnerId" && columnField != "StartDate" && columnField != "EndDate")
{
eventRow[columnField] = valueObject;
}
if hours are in 12-hour format, use lowercase hh, like this "yyyy/MM/dd hh:mm:ss.fff"
I have an 'IF' statement but I want the condition to check that the date of my object is not less than todays date but I can not figure out how to do this at all.
Code
private List<Web.Services.Entities.Generic.Expenditure> getTransactions(int Id, int AccountId, string Identifier)
{
if (Details != null)
{
foreach (var ABC in Details.Info.ABC)
{
if (ABC.Type == "Test" && ABC.Value.Value > 0)
{
int j = 1;
if (ABC.Frequency == "Monthly")
{
j = 3;
}
for (var i = 0; i < j; i++)
{
List.Add(new Web.Services.Entities.Generic.Expenditure
{
Amount = ABC.RegularIncome.Value * -1,
Description = "Income (" + ABC.Frequency + ")",
DueDate = (DateTime)ABC.NextDate.Value.AddMonths(i)
});
}
}
}
}
}
I tried to declare my (DateTime)ABC.NextDate.Value as a VAR above the following IF and then add to if (ABC.Type == "ABC" && ABC.Value.Value > 0) but I got the following error:
operator '&& ' cannot be applied to operands of type 'bool' and
'system.datetime'
I need to add another condition to the above IF and not replace the '0' as this is checking another value in what is returned.
To test a nullable date you do the following:
if (dateTimeToBeTested.Value.Date >= DateTime.Now.Date)
By using the .Date property, you are forcing the DateTime to midnight of the date in question, so time differences will be ignored.
To use this in your example above, you can do the following:
if (ABC.Type == "Test" && ABC.Value.Value > 0 && dateTimeToBeTested.Value.Date >= DateTime.Now.Date)
Use DateTime.Now to compare ABC.Value.Value with current date.
if (ABC.Type == "Test" && ABC.Value.Value > DateTime.Now)
Edit after question update with more required details and updated if statement.
System.Nullable' does not contain a definition for 'Date' and no
extension method 'Date' accepting...
You need to use DateTime.Value to access the Date property of nullable DateTime. Before using Date property you must check if DateTime variable has value. You can use .HasValue to ensure you have value for nullable DateTime.
Once you are sure that your datetime variable has values using .HasValue you can safely use DateProperty so you would use ABC.NextDate.Value instead of ABC.NextDate to access Date Property.
if (ABC.Type == "Test" && ABC.Value.Value > 0 && ABC.NextDate.HasValue && ABC.NextDate.Value.Date >= DateTime.Now.Date)
I doubt I am the only one who has come up with this solution, but if you have a better one please post it here. I simply want to leave this question here so I and others can search it later.
I needed to tell whether a valid date had been entered into a text box and this is the code that I came up with. I fire this when focus leaves the text box.
try
{
DateTime.Parse(startDateTextBox.Text);
}
catch
{
startDateTextBox.Text = DateTime.Today.ToShortDateString();
}
DateTime.TryParse
This I believe is faster and it means you dont have to use ugly try/catches :)
e.g
DateTime temp;
if(DateTime.TryParse(startDateTextBox.Text, out temp))
{
// Yay :)
}
else
{
// Aww.. :(
}
Don't use exceptions for flow control. Use DateTime.TryParse and DateTime.TryParseExact. Personally I prefer TryParseExact with a specific format, but I guess there are times when TryParse is better. Example use based on your original code:
DateTime value;
if (!DateTime.TryParse(startDateTextBox.Text, out value))
{
startDateTextox.Text = DateTime.Today.ToShortDateString();
}
Reasons for preferring this approach:
Clearer code (it says what it wants to do)
Better performance than catching and swallowing exceptions
This doesn't catch exceptions inappropriately - e.g. OutOfMemoryException, ThreadInterruptedException. (Your current code could be fixed to avoid this by just catching the relevant exception, but using TryParse would still be better.)
Here's another variation of the solution that returns true if the string can be converted to a DateTime type, and false otherwise.
public static bool IsDateTime(string txtDate)
{
DateTime tempDate;
return DateTime.TryParse(txtDate, out tempDate);
}
All the Answers are Quite great but if you want to use a single function ,this may work.
It will work with other date format but wont work with this date eg:05/06/202 it will consider it as valid date but it isnt.
private bool validateTime(string dateInString)
{
DateTime temp;
if (DateTime.TryParse(dateInString, out temp))
{
return true;
}
return false;
}
I would use the DateTime.TryParse() method: http://msdn.microsoft.com/en-us/library/system.datetime.tryparse.aspx
What about using TryParse?
A problem with using DateTime.TryParse is that it doesn't support the very common data-entry use case of dates entered without separators, e.g. 011508.
Here's an example of how to support this. (This is from a framework I'm building, so its signature is a little weird, but the core logic should be usable):
private static readonly Regex ShortDate = new Regex(#"^\d{6}$");
private static readonly Regex LongDate = new Regex(#"^\d{8}$");
public object Parse(object value, out string message)
{
msg = null;
string s = value.ToString().Trim();
if (s.Trim() == "")
{
return null;
}
else
{
if (ShortDate.Match(s).Success)
{
s = s.Substring(0, 2) + "/" + s.Substring(2, 2) + "/" + s.Substring(4, 2);
}
if (LongDate.Match(s).Success)
{
s = s.Substring(0, 2) + "/" + s.Substring(2, 2) + "/" + s.Substring(4, 4);
}
DateTime d = DateTime.MinValue;
if (DateTime.TryParse(s, out d))
{
return d;
}
else
{
message = String.Format("\"{0}\" is not a valid date.", s);
return null;
}
}
}
One liner:
if (DateTime.TryParse(value, out _)) {//dostuff}
protected bool ValidateBirthday(String date)
{
DateTime Temp;
if (DateTime.TryParse(date, out Temp) == true &&
Temp.Hour == 0 &&
Temp.Minute == 0 &&
Temp.Second == 0 &&
Temp.Millisecond == 0 &&
Temp > DateTime.MinValue)
return true;
else
return false;
}
//suppose that input string is short date format.
e.g. "2013/7/5" returns true or
"2013/2/31" returns false.
http://forums.asp.net/t/1250332.aspx/1
//bool booleanValue = ValidateBirthday("12:55"); returns false
private void btnEnter_Click(object sender, EventArgs e)
{
maskedTextBox1.Mask = "00/00/0000";
maskedTextBox1.ValidatingType = typeof(System.DateTime);
//if (!IsValidDOB(maskedTextBox1.Text))
if (!ValidateBirthday(maskedTextBox1.Text))
MessageBox.Show(" Not Valid");
else
MessageBox.Show("Valid");
}
// check date format dd/mm/yyyy. but not if year < 1 or > 2013.
public static bool IsValidDOB(string dob)
{
DateTime temp;
if (DateTime.TryParse(dob, out temp))
return (true);
else
return (false);
}
// checks date format dd/mm/yyyy and year > 1900!.
protected bool ValidateBirthday(String date)
{
DateTime Temp;
if (DateTime.TryParse(date, out Temp) == true &&
Temp.Year > 1900 &&
// Temp.Hour == 0 && Temp.Minute == 0 &&
//Temp.Second == 0 && Temp.Millisecond == 0 &&
Temp > DateTime.MinValue)
return (true);
else
return (false);
}
You can also define the DateTime format for a specific CultureInfo
public static bool IsDateTime(string tempDate)
{
DateTime fromDateValue;
var formats = new[] { "MM/dd/yyyy", "dd/MM/yyyy h:mm:ss", "MM/dd/yyyy hh:mm tt", "yyyy'-'MM'-'dd'T'HH':'mm':'ss" };
return DateTime.TryParseExact(tempDate, formats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out fromDateValue);
}
DateTime temp;
try
{
temp = Convert.ToDateTime(grd.Rows[e.RowIndex].Cells["dateg"].Value);
grd.Rows[e.RowIndex].Cells["dateg"].Value = temp.ToString("yyyy/MM/dd");
}
catch
{
MessageBox.Show("Sorry The date not valid", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop,MessageBoxDefaultButton.Button1,MessageBoxOptions .RightAlign);
grd.Rows[e.RowIndex].Cells["dateg"].Value = null;
}
DateTime temp;
try
{
temp = Convert.ToDateTime(date);
date = temp.ToString("yyyy/MM/dd");
}
catch
{
MessageBox.Show("Sorry The date not valid", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop,MessageBoxDefaultButton.Button1,MessageBoxOptions .RightAlign);
date = null;
}
protected static bool CheckDate(DateTime date)
{
if(new DateTime() == date)
return false;
else
return true;
}