As my title above I got a table in my database that is DateTime datatype and it is null value. And I got this line of code that I am using but I don't know why that it is returning 12:00
string FitaCorIn1 = Convert.ToDateTime(req.FACorrectionIn1).ToString("hh:mm") == null ? "00:00" : Convert.ToDateTime(req.FAIn1).ToString("hh:mm");
string FitaCorOut1 = Convert.ToDateTime(req.FACorrectionOut1).ToString("hh:mm") == null ? "00:00" : Convert.ToDateTime(req.FAIn1).ToString("hh:mm");
So as you can see in my code If the value of datetime is null I want to display 00:00 and if it is not null it will display the current value.
NOTE
12 Hours Format
You should check for null before converting them, otherwise you may get Exceptions from convert method. (As per the comments) It seems the FACorrectionIn1 is of type DateTime if so you have to check compare them with DateTime.MinValue if it is a nullable DateTime you can check for null as well.
Why you are getting 12:00 even when the value in the database is
null
Same reason FACorrectionIn1 is a DateTime object, and so it won't be null so the condition that check for null became false since it's default value is 01/01/0001 00:00:00. So when you format them using .ToString("hh:mm") you will get 12:00. So you have to do like this:
string FitaCorIn1 = req.FACorrectionIn1 == DateTime.MinValue ? "00:00" :
Convert.ToDateTime(req.FAIn1).ToString("hh:mm");
It would be great if you use parsing instead for Convert.To..
You should use HH:mm format.
Convert.ToDateTime(req.FAIn1).ToString("HH:mm");
I got it now.. Thanks to spencer7593.. This is my code looks like now.
string FitaCorIn1 = req.FACorrectionIn1 == null ? "00:00" : Convert.ToDateTime(req.FACorrectionIn1).ToString("hh:mm");
string FitaCorOut1 = req.FACorrectionOut1 == null ? "00:00" : Convert.ToDateTime(req.FACorrectionOut1).ToString("hh:mm");
Related
I have this line of code here:
command.Parameters["#DateCompleted"].Value = items[i].DateCompleted.Equals("01/01/0001 12:00:00 AM") ? null : items[i].DateCompleted;
but I got this error:
Type of conditional expression cannot be determined because there is no implicit conversion between '<null>' and 'System.DateTime'
What I am trying to do is not use the 01/01/0001 Date and use null because the item is null.
Additional Code:
command.Parameters.Add("#DateCompleted", System.Data.SqlDbType.DateTime);
Simply cast the null to a DateTime?. Also, assuming DateCompleted is a DateTime (it should be), then don't compare against a string, but against DateTime.MinValue instead.
command.Parameters["#DateCompleted"].Value =
items[i].DateCompleted.Equals(DateTime.MinValue)
? (DateTime?) null
: items[i].DateCompleted;
Use DateTime?
command.Parameters["#DateCompleted"].Value =
items[i].DateCompleted.Equals("01/01/0001 12:00:00 AM") ? (DateTime?)null :
items[i].DateCompleted;
To use the ternary operator where one of the return types is null, the other return type has to be a nullable type, which DateTime is not, being a struct. What you could do is replace the null with default(DateTime):
DateTime value = someCondition ? default(DateTime) : items[i].DateCompleted;
How do I concatenate a nullable datetime into a textbox in c# asp.net to show just date?
When i load the date into the textbox I get below in textbox:
2014-04-26 00:00:00.000
But I just want the date any ideas? Cant get tostring to display what i want.
I am calling the value like below:
txtDateExpected.Text = loadVisitDetails.expectedDate.ToString();
you can get only Date part by using Date property of DateTime class:
txtDateExpected.Text = loadVisitDetails.expectedDate != null ? loadVisitDetails.expectedDate.Date.ToString() : "";
or:
if(loadVisitDetails.expectedDate != null)
txtDateExpected.Text = loadVisitDetails.expectedDate.Date.ToString();
Check Here DateTime.Date MSDN docs
Use string.Format to form a representation you want:
DateTime? dt = loadVisitDetails.expectedDate;
txtDateExpected.Text = (dt == null) ?
String.Empty :
String.Format("{0:yyyy-MM-dd}", dt);
I want to check passed value is null or datetime value using ternary operator in c#?
I tried like this
fromDate == null ? null : Convert.ToDateTime(fromDate)
getting error:
type of conditional expression cannot be determined
I want to check whether variable fromDate is null or having date time value ?
variable fromDate is coming from Querystring and type of string.
From ?: Operator:
Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.
condition ? first_expression : second_expression;
Convert.ToDateTime returns DateTime and there is no implicit conversion between null and DateTime. And the conditional operator is an expression and that needs a return type.
One option seems logical to me using DateTime.TryParse (which returns boolean) as a first expression and use another boolean (true or false) as a second expression. Damiths' answer seems logical.
Or instead you can use nullable DateTime like DateTime?
DateTime? foo;
if(foo.HasValue)
{
//Nullable DateTime has a value..
}
if you have string value for fromDate do as below
DateTime dt;
bool isValidDate = String.IsNullOrEmpty(fromDate) ? false : DateTime.TryParse(fromDate, out dt);
if you know the datetime format/formats which your input having you better use DateTime.TryParseExact method
if fromDate is DateTime, then simple you can check as below
fromDate.HasValue
you don't need ?: Operator
The problem is that Convert.ToDateTime(fromDate) is of type DateTime, which cannot accept a null value, that is why this code won't work in this form. You have two choices to make. Either change it to regular if:
if(fromDate != null)
{
Convert.ToDateTime(fromDate)
}
Or cast DateTime to nullable DateTime:
fromDate == null ? null : (DateTime?)Convert.ToDateTime(fromDate)
Ternary operator in C# needs both values to be of the same type and it is explained here.
romDate == null ? null : Convert.ToDateTime(fromDate)
null and Convert.ToDateTime(fromDate) haven't common type. Compiler must be able to cast both expressions in canditional operator to same type.
I hope it will help you
string format = "ddd dd MMM h:mm tt yyyy";
DateTime dateTime;
fromDate=(DateTime.TryParseExact(fromDate, format, CultureInfo.InvariantCulture,
DateTimeStyles.None, out dateTime))?dateTime:null;
you must use String.IsNullOrEmpty to check if fromDate is null like this:
DateTime? date = String.IsNullOrEmpty(fromDte) ? null : (DateTime?)Convert.ToDateTime(fromDate)
It looks like the main problem is that you are trying to assign null to a DateTime
DateTime is a structure and not a reference type so this can't be done.
Either use a nullable DateTime (DateTime?) or a specific value to indicate null, such as DateTime.MinValue
Have a look here for an example: http://www.dotnetperls.com/nullable-datetime
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;
}
}
How could we handle null for a datetime field (got from SQL Server) in our program in c#?
There are 3 common approaches here;
if you are talking about object (perhaps as you fetch it from a data-reader), then DBNull.Value can represent null. I don't tend to let this out of the data-layer, though
due to .NET 1.1 history, DateTime.MinValue is commonly interpreted as null; a magic number, maybe - but it works and is supported by most data-binding etc
in .NET 2.0, Nullable<T> means you can use DateTime? - i.e. a nullable-of-DateTime; just use DateTime? where-ever you mean a DateTime that can be null, and you can give it a value of null or a valid DateTime.
Some other thoughts on data-access and nulls:
when passing to a SqlCommand you must use DBNull.Value, not null - see below
when reading from a data-reader, I tend to check reader.IsDbNull(ordinal)
command stuff (with Nullable<T> as the example):
param.Value = when.HasValue ? (object)when.Value : DBNull.Value;
Use DateTime?
What problem are you having, specifically?
-- Edit
Just so it's clear, that's a Nullable DateTime object, not a question :)
DateTime? t = null;
-- Edit
Responding to comment, check it like so:
DateTime? theTime;
if( table["TheColumn"] == DBNull.Value ){
theTime = null;
} else {
theTime = (DateTime) table["TheColumn"];
}