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;
Related
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");
My ProcessDate type is DateTime? when i use ToString it is showing that exception.
dfCalPlanDate.Text = concreteCalPlan.ProcessDate.ToString("d");
Thank you for your interested.
Simple: Nullable<T> (and, thus, Nullable<DateTime>, aka DateTime?) does not have a method ToString(String).
You probably wanted to invoke DateTime.ToString(String). To do this in a null-safe way, you can use C# 6's null-conditional operator ?.:
dfCalPlanDate.Text = concreteCalPlan.ProcessDate?.ToString("d");
which is a concise way of writing:
var date = concreteCalPlan.ProcessDate;
dfCalPlanDate.Text = (date == null ? null : date.Value.ToString("d"));
Note that this will yield null if ProcessDate is null. You can append the null-coalescing operator ?? if you need another result in that case:
dfCalPlanDate.Text = concreteCalPlan.ProcessDate?.ToString("d") ?? "no date set";
ProcessDate is not a DateTime. ProcessDate.Value is. You need to do:
dfCalPlanDate.Text = concreteCalPlan.ProcessDate.Value.ToString("d");
Remember to check if the DateTime? has a value first.
I have an issue that I'd like to work around
I have declared a nullable DateTime and I'm trying to put either a date in it or a null value using a ternary operator.
This does not work:
DateTime? date;
date = getDate() == DateTime.MinValue ? null : getDate()
My own code is a bit more elaborate but basically what I'd like to use is
date = getDate() == DateTime.MinValue ? null : resultofgetDate()withoutactuallyrunningitagain
I don't want to do the function twice, but in this case as a bonus, since it's datetimes, it also gives an error in the else section saying
There is no implicit conversion between 'null' and 'System.DateTime' in my first example.
I'm not sure in what direction to look. I seem to need the opposite of the null coalescing operator (??).
There is no such operator. You can write something like this:
DateTime? date = getDate();
date = date == DateTime.MinValue ? null : date;
It seems as if getDate() is returning a DateTime and not a DateTime? (aka Nullable<DateTime>). The values used in ternary expressions have to be of the same type which is why you are getting your error.
Your first example should work with
date = getDate() == DateTime.MinValue ? null : (DateTime?)getDate()`
as pointed out in MaKCbIMKo's answer.
I'm assuming you return DateTime.MinValue as some sort of error handling / validation. If you change the method signature so it returns a DateTime? you can return null instead, then your statement becomes date = getDate()
Have you tried something like:
DateTime? date;
var dt = getDate();
date = dt == DateTime.MinValue ? (DateTime?)null : dt;
Hope it will help.
Please, do it as Rob described, but here is my take on an extension method:
public static T? Test<T>(this T? value, Predicate<T?> test, T? ifEquals) where T : struct
{
if (test(value))
{
return ifEquals;
}
return value;
}
Use it like this:
DateTime? d = GetDate().Test(t => t == DateTime.MinValue, null);
You can also create this extension method (one of the overloads calls the other one):
public static T? NullIfHasDefaultValue<T>(this T v) where T : struct
{
return EqualityComparer<T>.Default.Equals(v, default(T)) ? (T?)null : v;
}
public static T? NullIfHasDefaultValue<T>(this T? n) where T : struct
{
return n.GetValueOrDefault().NullIfHasDefaultValue();
}
Of course use it as getDate().NullIfHasDefaultValue().
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
When I do the following I get:
inv.RSV = pid.RSVDate
I get the following: cannot implicitly convert type System.DateTime? to System.DateTime.
In this case, inv.RSV is DateTime and pid.RSVDate is DateTime?
I tried the following but was not successful:
if (pid.RSVDate != null)
{
inv.RSV = pid.RSVDate != null ? pid.RSVDate : (DateTime?)null;
}
If pid.RSVDate is null, I like to not assign inv.RSV anything in which case it will be null.
DateTime can't be null. It's default is DateTime.MinValue.
What you want to do is the following:
if (pid.RSVDate.HasValue)
{
inv.RSV = pid.RSVDate.Value;
}
Or, more succinctly:
inv.RSV = pid.RSVDate ?? DateTime.MinValue;
You need to make the RSV property nullable too, or choose a default value for the case where RSVDate is null.
inv.RSV = pid.RSVDate ?? DateTime.MinValue;
Because inv.RSV is not a nullable field, it can't be NULL. When you initialize your object, it is a defaulting inv.RSV to an empty DateTime, the same as you would get if you said
inv.RSV = new DateTime()
So, if you want to set inv.RSV to pid.RSV if it's not NULL, or the default DateTime value is it is null, do this:
inv.RSV = pid.RSVDate.GetValueOrDefault()
if the one being assigned into as a DateTime and the one being assigned from is DateTime?, you could use
int.RSV = pid.RSVDate.GetValueOrDefault();
This supports an overload that allows you to specify the default value, if the default for DateTime is not ideal.
If pid.RSVDate is null, I like to not assign inv.RSV anything in which
case it will be null.
int.RSV will not be null, as you have already said it's DateTime, not a nullable type. If it is never assigned by you, it will have the default value of it's type, which is DateTime.MinValue, or January 1, 0001.
inv.RSV was null to begin with. How do I say do not update it there is no value for pid.RSVDate
Again, this simply cannot be, given your description of the property. However, if generally speaking you do not want to update inv.RSV if pid.RSVDate is null (and you're just getting mixed up in your words), then you would simply write an if check around the assignment.
if (pid.RSVDate != null)
{
inv.RSV = pid.RSVDate.Value;
}
pid.RSVDate has the possibility of being null, whereas inv.RSV does not, so what would happen if RSVDate is null?
You need to check if the value is null before -
if(pid.RSVDate.HasValue)
inv.RSV = pid.RSVDate.Value;
But what would the value of inv.RSV be if RSVDate is null? Is there always going to be a date in this property? If so, you could use the ?? operator to assign a default if you want to.
pid.RSV = pid.RSVDate ?? myDefaultDateTime;