How can I get DateTime value in C# from row, the current code is giving me error
any help is appreciated, the data is coming in from progress database:
foreach (DataRow r in ds.Tables[0].Rows)
{
string prodCode = r["PRD-CDE"].ToString();
statCode = r["STAT"].ToString();
DateTime firstIssueDate = (DateTime)(r["FISS"]);
DateTime endIssueDate = (DateTime)(r["EISS"]);
if(endIssueDate > DateTime.Now)
{ /*do some thing...*/}
else {/*user invalid...*/}
}
there are two ways used in getting date convert and pars, thank you all for the help
Final working Code snippet:
foreach (DataRow r in ds.Tables[0].Rows)
{
string prodCode = r["PRD-CDE"].ToString(),statCode = r["STAT"].ToString();
// r.<DateTime?>("FISS");
if (r["FISS"] != DBNull.Value)
{
DateTime firstIssueDate = Convert.ToDateTime(r["FISS"]);
if (r["EISS"] != DBNull.Value)
{
DateTime endIssueDate = DateTime.Parse(r["EISS"].ToString());
if (endIssueDate > DateTime.Now)
{
This is just a guess but if the corresponding type in the database is DateTime, could you check if the column is nullable?
If so you may want to do a check r["column"] == DBNull.Value and then pass it to a nullable DateTime? Field.
Or even easier:
row.Field<DateTime?>("column")
If it isn't then yeah, Convert.ToDateTime() or something else should do it.
EDIT:
I see your final code there but is there any chance you want to do this:
DateTime? firstIssueDate = r.Field<DateTime?>("fiss");
DateTime? endIssueDate = r.Field<DateTime?>("eiss");
if (firstIssueDate.HasValue && endIssueDate.HasValue)
{
firstIssueDate.Value // blah blah
endIssueDate.Value // blah blah
}
I would recommend using DateTime.Parse() if the row is returning a string for that index.
string prodCode = r["PRD-CDE"].ToString(),statCode = r["STAT"].ToString();
DateTime firstIssueDate = DateTime.Parse(r["FISS"].ToString());
DateTime endIssueDate = DateTime.Parse(r["EISS"].ToString());
You could also use TryParse depending on your needs.
If you want to use a default value (such as DateTime.MinValue), rather than null (DateTime?) or DBNull, you could do this:
var firstIssueDate = r["FISS"] as DateTime? ?? DateTime.MinValue;
var endIssueDate = r["EISS"] as DateTime? ?? DateTime.MinValue;
foreach (DataRow r in ds.Tables[0].Rows)
{
string prodCode = r["PRD-CDE"].ToString();
string statCode = r["STAT"].ToString();
DateTime firstIssueDate = DateTime.Parse((r["FISS"]).ToString());
DateTime endIssueDate = DateTime.Parse((r["EISS"]).ToString());
if(endIssueDate > DateTime.Now)
{ /*do some thing...*/}
else {/*user invalid...*/}
}
This should compile and may work for you. Though it is certainly not performing any error checking that you should do for production code. Also look into DateTime.TryParse and you may to look into adding a IFormatProvider to ensure the format is parsed as expected.
First of all, do r["FISS"].GetType() and print it to console (or pause and look at it in the debugger). If it says it's a String, then most of the above advices will help. If it says something else, please come back and update your question.
As a side answer, you could use also the static function Convert.ToDateTime
DateTime.Parse(r["FISS"].ToString()) is the way to go, but it throws a "String was not recognized as a valid DateTime" error. Could you show the actual string in the r["FISS"] column, it might be a internationalisation problem....
If you have a DateTime string with a special format (not any standard .NET DateTime format) that needs to be converted to .NET DateTime type, you can use DateTime.ParseExact() method.
Please see the MSDN document for more details including examples.
If you have multiple formats to parse, try DateTime.ParseExact Method (String, String[], IFormatProvider, DateTimeStyles)
Related
I have a problem.
This is not working
> var from = "";
> StartDTime = Convert.ToDateTime(from);
This is working
> var from = "2021-10-05";
> StartDTime = Convert.ToDateTime(from);
Some time I'm sending Date Value, but sometime in not sending Date Value.in that time from variable pass as a empty string. I want to set if from variable is = "" then need to set default Date Value.so how can I resolve this?. Please help me guys. Thank you
A safe way of doing that would be:
StartDTime = string.IsNullOrEmpty(from) ? DateTime.Now : DateTime.Parse(from);
But if you have control over the code passing the "from" variable, you can declare it as nullable DateTime, then your code would look like this:
DateTime? from = null;
var StartDTime = from.HasValue ? from.Value : DateTime.Now;
Which for short would be:
StartDTime = from ?? DateTime.Now;
DateTime.TryParse will do the job for you:
for example:
DateTime dateTime;
var from = "";
DateTime.TryParse(from, out dateTime);
One-liner, with only the validation you specify:
StartDTime = from == "" ? new DateTime() : Convert.ToDateTime(from);
It's not ellegant, but works.
var from = "";
if(from == ""){ from = DateTime.MinValue.ToString(); }
DateTime StartDTime = Convert.ToDateTime(from);
But i think that a nullable DateTime would be more elegant, like this:
var from = null;
DateTime? StartDTime = from;
Or you can set a default date, like this:
var from = null;
DateTime? StartDTime = from ?? YourDefaultDate;
Convert methods either successfully convert the string passed to it, or throws an error, that's the way it's supposed to work. For most data types there are also TryParse methods that return true/false based on if it converted successfully and have an output variable which will be DateTime.MinValue if it failed. This is how I would handle your situation:
DateTime startDTime;
string from = "";
if (!DateTime.TryParse(from, out startDTime)){
startDTime = DateTime.Now;
}
This will set the startTime to the date passed in from, but if no date was passed it sets it to the current date and time - if you want a different default value, that replaces new DateTime() and if your default should be January 1, 0001, then you can just use the TryParse part directly, since that's the automatic default for a failed TryParse.
I want to add a date in session (date1) like this:
Session["DateLesson"] = date1.ToString("dd.MM.yyyy");
Now from the session I want take this value:
var asd = Session["DateLesson"];
/*asd = "20.04.2012"*/
var datelesson = DateTime.Parse((string) asd);
And it gives me this exception:
FormatException not recognized as a valid DateTime
A period is not a valid/standard separator character in most locales. You'll need to use DateTime.ParseExact() in combination with a format string to tell the function how to read it. More importantly, if reading it back to a datetime is your main goal, why not just put the datetime in the session as is? That seems way more efficient, easier, and more maintainable to me.
Why persist your date as a string?
You could simply store it like this:
Session["DateLesson"] = date1;
And then retrieve it like this:
var datelesson = (DateTime)Session["DateLesson"];
string value = "20.04.2012";
DateTime datetime = DateTime.ParseExact(value, "dd.MM.yyyy", null);
This will return 4/20/2012 12:00:00:00 AM
Don't keep value as a string but as an object of the initial type:
public DateTime? DateLesson
{
get
{
DateTime? dateTime = Session["DateLesson"] as DateTime?;
if (dateTime.HasValue) // not null
{
// use dateTime.Value
}
}
set
{
Session["DateLesson"] = value;
}
}
I would declare an empty String variable like this:
string myString = string.Empty;
Is there an equivalent for a 'DateTime' variable ?
Update :
The problem is I use this 'DateTime' as a parameter for a 'StoredProcedure' in SQL.
E.g:
DateTime? someDate = null;
myCommand.Parameters.AddWithValue("#SurgeryDate", someDate);
When I run this code an exception is catched telling me the 'StoredProcedure' expected a '#SurgeryDate' parameter.
But i provided it.
Any idea why?
Since DateTime is a value type you cannot assign null to it, but exactly for these cases (absence of a value) Nullable<T> was introduced - use a nullable DateTime instead:
DateTime? myTime = null;
No. You have 2 options:
DateTime date = DateTime.MinValue;
This works when you need to do something every X amount of time (since you will always be over MinValue) but can actually cause subtle errors (such as using some operators w/o first checking if you are not MinValue) if you are not careful.
And you can use Nullable:
DateTime? date = null;
Which is nice and avoids most issues while introducing only 1 or 2.
It really depends on what you are trying to achieve.
You can set a DateTime variable to be '1/1/0001 00:00:00' but the variable itself cannot be null. To get this MinTime use:
DateTime variableName = DateTime.MinValue;
You may want to use a nullable datetime. Datetime? someDate = null;
You may find instances of people using DateTime.Max or DateTime.Min in such instances, but I highly doubt you want to do that. It leads to bugs with edge cases, code that's harder to read, etc.
The method you used (AddWithValue) doesn't convert null values to database nulls. You should use DBNull.Value instead:
myCommand.Parameters.AddWithValue(
"#SurgeryDate",
someDate == null ? DBNull.Value : (object)someDate
);
This will pass the someDate value if it is not null, or DBNull.Value otherwise. In this case correct value will be passed to the database.
Either:
DateTime dt = new DateTime();
or
DateTime dt = default(DateTime);
If you set the date to
DateTime dNewDate = new DateTime();
The value is set to {1/1/0001 12:00:00 AM}
Option 1: Use a nullable DateTime?
Option 2: Use DateTime.MinValue
Personally, I'd prefer option 1.
A string is a sequence of characters. So it makes sense to have an empty string, which is just an empty sequence of characters.
But DateTime is just a single value, so it's doesn't make sense to talk about an “empty” DateTime.
If you want to represent the concept of “no value”, that's represented as null in .Net. And if you want to use that with value types, you need to explicitly make them nullable. That means either using Nullable<DateTime>, or the equivalent DateTime?.
DateTime (just like all value types) also has a default value, that's assigned to uninitialized fields and you can also get it by new DateTime() or default(DateTime). But you probably don't want to use it, since it represents valid date: 1.1.0001 0:00:00.
There's no such thing as an empty date per se, do you mean something like:
DateTime? myDateTime = null;
The .addwithvalue needs dbnull.
You could do something like this:
DateTime? someDate = null;
//...
if (someDate == null)
myCommand.Parameters.AddWithValue("#SurgeryDate", DBnull.value);
or use a method extension...
public static class Extensions
{
public static SqlParameter AddWithNullValue(this SqlParameterCollection collection, string parameterName, object value)
{
if (value == null)
return collection.AddWithValue(parameterName, DBNull.Value);
else
return collection.AddWithValue(parameterName, value);
}
}
This will work for null able dateTime parameter
. .
SearchUsingDate(DateTime? StartDate, DateTime? EndDate){
DateTime LastDate;
if (EndDate != null)
{
LastDate = (DateTime)EndDate;
LastDate = LastDate.AddDays(1);
EndDate = LastDate;
}
}
I have string which contains a time (obtained from a DB):
string user_time = "17:10:03"; //Hours:minutes:seconds
DateTime time_now = DateTime.Now;
How do I compare this string to a DateTime? I'd like something like this:
if(time_now > user_time)
{
//Do something
}
else
{
//Do something
}
DateTime supports comparison, but first you need to parse the date-time string, DateTime.Parse() should suffice:
var dateTimeStr = "17:10:03";
var user_time = DateTime.Parse( dateTimeStr );
var time_now = DateTime.Now;
if( time_now > user_time )
{
// your code...
}
Bear in mind, that comparing dates/times sometimes requires awareness of time-zones to make the comparison meaningful.
The problem is that DateTime.Now includes a date, "17:10:03" doesn't. Do it like this:
Dim dbaseTime As TimeSpan = TimeSpan.Parse("17:10:03")
If DateTime.Now.TimeOfDay > dbaseTime Then
Console.WriteLine("Let's go home")
End If
Do everything in your power to convert that string column type to a datetime column.
You can use DateTime.Compare() along with DateTime.Parse() to convert the string to a DateTime object.
DateTime.Parse Will convert the string into a DateTime object which you can then use to compare.
if (DateTime.Now > DateTime.Parse(user_time))
{
...
}
But you really shouldn't store a time as a string, you should use the native time or datetime format of your database, that way you could use the value of the time in your queries, and index them properly.
if (time_now > Date.Parse(DBString)) {
} else {
}
I have an output data class with a DateTime variable. I want to clear that to a null value in a loader class but the compiler complains with:
Cannot convert null to 'System.Data.Time' because it is a non-nullable value type.
I understand that, but if I change the type to DateTime? creating the nullable type wrapper I get:
No overload for method 'ToString' takes '1' arguments
I have an output line that reads.
ACCOUNT_ESTABLISHED_DATE.ToString("yyyy-MM-dd")
So the question is, when I set the DateTime as nullable, how do I get around the fact that is no longer behaves like a DateTime that has the formatted ToString available?
Use its Value property, like so:
DateTime? dt = DateTime.Now; // or whatever
MessageBox.Show(dt.Value.ToString(...));
try
ACCOUNT_ESTABLISHED_DATE.Value.ToString("yyyy-MM-dd")
You need to access the actual value using the 'Value' property of the nullable type.
You should make sure 'Value' contains something first testing the ACCOUNT_ESTABLISHED_DATE.HasValue property.
HTH
Whenever you wrap something Nullable<> (which is what you're doing with DateTime?), you need to do obj.Value.ToString().
You should write:
ACCOUNT_ESTABLISHED_DATE.Value.ToString("yyyy-MM-dd")
.NET doesn't have a method out of the box for this. You'd need to have a helper method like:
public string Format(DateTime? date, string format)
{
if (date == null)
return string.Empty;
return date.Value.ToString(format);
}
Or even better, an extension method for DateTime?:
public static class DateTimeExtensionMethods
{
public static string ToString(this DateTime? date, string format)
{
if (date == null)
return string.Empty;
return date.Value.ToString(format);
}
}
Then to use your extension method, just use the code you have in your question and make sure the namespace of the DateTimeExtensionMethods is imported into your class.
are you looking for
DateTime? dt = new DateTime();
or
Nullable<DateTime> dt = new DateTime();
ACCOUNT_ESTABLISHED_DATE.Value.ToString("yyyy-MM-dd");
You would have to use
dt.HasValue ? dt.Value.ToString("...") : dt.ToString();
This is because Nullable<T> is a proper type in its own right whose ToString() method is already nicely done, as it handles the null case well. But to get to the underlying non-nullable object you have to use the Value property. But then you'll have to check for null (or HasValue) yourself.
Have you looked at setting the DateTime to DataTime.MinValue?
Suggested here http://dotnetperls.com/datetime-null-minvalue
DateTime? date = getSomeDate();
if (date != null) {
date.Value.ToString("yyyy-MM-dd");
}
string strDate = string.Empty;
if(ACCOUNT_ESTABLISHED_DATE != null)
{
strDate = ACCOUNT_ESTABLISHED_DATE.Value.ToString("yyyy-MM-dd");
}
or you can use null collacing operator
DateTime newDate = ACCOUNT_ESTABLISHED_DATE ?? new Date();
newDate.ToString("yyyy-MM-dd");