Nullable DateTime setting it getting invalid argument with cannot convert to long - c#

Why do I need to set DateTime as Nullable like this?
DateTime? Err_Rpt_Tm = new DateTime?(DateTime.Now);
Console.WriteLine(Err_Rpt_Tm);
Because I find it odd that in Linqpad when I do this
DateTime Err_Rpt_Tm = new DateTime(DateTime.Now);
I get this error
The best overloaded method match for 'System.DateTime.DateTime(long)' has some invalid arguments
Argument 1: cannot convert from 'System.DateTime' to 'long'
DateTime.Now is never going to be null, so I don't understand the need for nullable DateTime?
convert System.DateTime to long??? I'm explicitly setting DateTime variable "Err_Rpt_Tm"

DateTime? is a short-hand for Nullable<DateTime>. Let's look at documentation on MSDN. In constructors section the only available constructor is Nullable<T>(T). This explains why first part of your code compiles.
In second case you are trying to initialize DateTime, and MSDN clearly states that there is no constructor, that accepts single parameter of type DateTime. This is why you get a compile error in second case.
To fix the issue you can use much simpler form of initialization:
DateTime? Err_Rpt_Tm = DateTime.Now;
DateTime Err_Rpt_Tm2 = DateTime.Now;
This is possible because Nullable<T> implements operators for converting nullable type to / from actual type.

No DateTime constructor accepts DateTime object although it has constructor for long i.e. DateTime(long ticks) and error is suggesting that constructor to be used.
You can directly assign DateTime.Now to DateTime object and do not need a constructor for this.
DateTime Err_Rpt_Tm = DateTime.Now;
To assign to Nullable DateTime
DateTime? Err_Rpt_Tm = DateTime.Now;

Related

How do I convert a DateTimeOffset? to DateTime in C#?

I need to convert a DateTimeOffset? to a DateTime. The value originally comes from a XAML CalendarDatePicker, but I need to change it to DateTime to store the value. I have found this description of how to convert DateTimeOffset, but I do not think that it answers my question because they don't use a nullable type.
Nullable types are useful, but can sometimes be confusing at first. The Nullable<T> is a struct where T is a struct as well. This struct wraps the value for the instance variable T and exposes three primary members.
HasValue // Returns bool indicating whether there is a value present.
Value // Returns the value of T if one is present, or throws.
GetValueOrDefault() // Gets the value or returns default(T).
You can make any struct nullable by adding a '?' after the declaration of the variable type, or by wrapping the variable type with Nullable< varible type here >. As depicted below:
Nullable<DateTimeOffset> a = null;
DateTimeOffset? b = null;
I believe that what you would want here is to check if there is in fact a value with .HasValue and then take the .Value from the offset and perform your standard conversion.
Example
var now = DateTime.Now;
DateTimeOffset? offset = now;
DateTime dateTime = offset.HasValue ? offset.Value.DateTime : DateTime.MaxValue;
Or if you want a DateTime? do this:
var now = DateTime.Now;
DateTimeOffset? offset = now;
DateTime? dateTime = offset.HasValue ? offset.Value.DateTime : (DateTime?)null;

How to check if DateTime object is null

I'm looking to validate a DateTime variable to ensure that it isn't blank on the UI. The string equivalent checking would be String.IsNullOrEmpty(), but how would I go about it with my DateTime variable?
DateTime is a value type, so it cannot be null. To check if a DateTime variable has the default (all 0) value you can compare it with new DateTime() or default(DateTime).
Another option would be to use DateTime? instead of DateTime for user input and check HasValue property.
To check if a DateTime is null in C#, you must first ensure the DateTime is nullable.
// DateTime? means it is nullable
var DateTime? date = null;
// .HasValue only exists if DateTime is nullable
if(date.HasValue)
Console.WriteLine("date has a value");
else
Console.WriteLine("date is null");
If your DateTime is not nullable, make it nullable (unless you are absolutely certain in will never be null). You don't want to go down the road of assigning "nullish" values to your DateTimes. In my experience, this creates confusing bugs / code.

Get short date for System Nullable datetime (datetime ?) in C#

How to get short date for Get short date for System Nullable datetime (datetime ?)
for ed 12/31/2013 12:00:00 --> only should return 12/31/2013.
I don't see the ToShortDateString available.
You need to use .Value first (Since it's nullable).
var shortString = yourDate.Value.ToShortDateString();
But also check that yourDate has a value:
if (yourDate.HasValue) {
var shortString = yourDate.Value.ToShortDateString();
}
string.Format("{0:d}", dt); works:
DateTime? dt = (DateTime?)DateTime.Now;
string dateToday = string.Format("{0:d}", dt);
Demo
If the DateTime? is null this returns an empty string.
Note that the "d" custom format specifier is identical to ToShortDateString.
That function is absolutely available within the DateTime class. Please refer to the MSDN documentation for the class: http://msdn.microsoft.com/en-us/library/system.datetime.toshortdatestring.aspx
Since Nullable is a generic on top of the DateTime class you will need to use the .Value property of the DateTime? instance to call the underlying class methods as seen below:
DateTime? date;
String shortDateString;
shortDateString = date.Value.ToShortDateString();
Just be aware that if you attempt this while date is null an exception will be thrown.
If you want to be guaranteed to have a value to display, you can use GetValueOrDefault() in conjunction with the ToShortDateString method that other postelike this:
yourDate.GetValueOrDefault().ToShortDateString();
This will show 01/01/0001 if the value happened to be null.
Check if it has value, then get required date
if (nullDate.HasValue)
{
nullDate.Value.ToShortDateString();
}
Try
if (nullDate.HasValue)
{
nullDate.Value.ToShortDateString();
}
If you are using .cshtml then you can use as
<td>#(item.InvoiceDate==null?"":DateTime.Parse(item.YourDate.ToString()).ToShortDateString())</td>
or if you try to find short date in action or method in c# then
yourDate.GetValueOrDefault().ToShortDateString();
And is already answered above by Steve.
I have shared this as i used in my project. it works fine. Thank you.

why it throws an exception,if its same type date time

Am just trying to understand why this exception throws.
Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists (are you missing a cast?)
This is what am trying to do
story.BroadcastOn is a date time value am getting from database (eg: 23/03/2012 1:56 Pm).
Am trying to convert the time from 12 to 24 hrs format,this is what i was trying to do
DateTime testconverttime = story.BroadcastOn;`//this is where it throws exception
so i have to use the parse to get rid of this like below to solve my issue but it doesn't make sense to me
if (!string.IsNullOrEmpty(story.BroadcastOn.ToString()))
{
DateTime localTime = story.BroadcastOn.Value;//Thanks all for the great suggestion.
converttime = localTime.ToString("dd/MMM/yyyy HH:mm ", CultureInfo.CurrentCulture);
}
already i converted my 12 hrs to 24hrs but trying to understand the exception,some one will give me an explanation please.
DateTime testconverttime = story.BroadcastOn.Value;
It's a nullable type (can have the null state also)
A nullable value type (DateTime is a value type), has the concept of the null value (no value). So if for example a column of datetime in database has nulls, then you can use Nullable<DateTime> or in short DateTime? to store the values which comes from that column.
About DateTime.ToString() and String.ToDateTime(): this is called yo-yo programming. You probably saw with Debuger that there is a representation of valid DateTime, which was giving by calling ToString(), but, in future, don't try to cast a type to another type via this yo-yo technique.
Try this, assuming the nullable type has a value:
DateTime testconverttime = story.BroadcastOn.Value;
DateTime? and DateTime are not the same type. DateTime? is the nullable version of the DateTime type.
You should check whether it's null, and then either cast or retrieve the value of the nullable:
if (story.BroadcastOn.HasValue) {
var broadcastOn = story.BroadcastOn.Value;
// do stuff with broadcastOn
} else {
// handle null BroadcastOn
}
or
if (story.BroadcastOn != null) {
var broadcastOn = (DateTime) story.BroadcastOn;
// do stuff with broadcastOn
} else {
// handle null BroadcastOn
}
Using .HasValue or comparing with null, and using .Value and casting to the non-nullable type should be equivalent. You can also use the ?? operator.
Try casting it as a DateTime, like so:
DateTime testconverttime = (DateTime)story.BroadcastOn
System.DateTime? and System.DateTime are 2 different types. You need to use story.BroadcastOn.Value if you are sure if it is not null.
DateTime? and DateTime are not the same type so you can not implicitly assign DateTime? to DateTime
You need to either explicitly cast it or assign the value via the Value property of DateTime. However, if BroadcastOn is null, either method will throw an exception.
If you don't know BroadcastOn is not null then you best option to is use the null-coalescing operator:
DateTime dt = story.BroadcastOn ?? default(DateTime);

Working with nullable DateTime

I am using LINQ and have a few properties thats DateTime? type.
If i now want to add the value from a textbox i cant seem to get this to work.
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_ScoringLastUpgrade", DbType="Date")]
public System.Nullable<System.DateTime> ScoringLastUpgrade
The textbox i use i have made sure with javascript that the format will be '2011-06-17'
But now when i try to do this:
myObject.ScoringLastUpgrade = Convert.ToDateTime(txtScoringUpgradeDate.Text).ToShortDateString();
I get this error: "Cannot convert type string to DateTime?"
How to do this?
The .ToShortDateString() call is converting it into a string. You should remove that call.
Also, you say you've made sure of the format with javascript. What if the user doesn't have javascript, you should do server-side checks too. Also, since it's in a given format, you can use DateTime.ParseExact or DateTime.TryParseExact (so an invalid format doesn't throw an exception) since its more efficient. (The format string would be "yyyy-MM-dd") i believe.
Don't convert it to string using 'ToShortDateTimeString', just set the result of Convert.ToDateTime:
myObject.ScoringLastUpgrade = Convert.ToDateTime(txtScoringUpgradeDate.Text);
Assuming you've done sufficient validation on txtScoringUpgradeDate.Text?
My preference when dealing with these type conversions is to use the TryParse method, e.g.:
DateTime date;
if (DateTime.TryParse(txtScoringUpgradeDate.Text, out date))
myObject.ScoringLastUpgrade = date;
The Convert.ToDateTime, much like the explicit DateTime.Parse will throw an InvalidCastException when an excepional value occurs. It's better to make your code fault tollerant then needlesly catch an exception.
UPDATE: based on your last comment:
You shouldn't return DateTime.MinValue in this case, as MinValue is less than the supported min value of a datetime column. the CLR DateTime supports a date range down to 0000-01-01, whereas the SQL datetime (as well as the comparative CLR SqlDateTime type) supports a minimum value of 1753-01-01. As it as a nullable DateTime, you should set it to null:
public static DateTime? ToNullableDateTime(this string date)
{
DateTime dateTime;
return (DateTime.TryParse(date, out dateTime))
? (DateTime?)dateTime
: null;
}
The problem is that you have put ToShortDateString() at the end there, effectively converting the DateTime back to a string again. Try removing that part of the line.
In my case (.cshtml):
<td>#item.InvoiceDate.Value.ToShortDateString().ToString()</td>
Where InvoiceDtae is Nullable Date in DB

Categories