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.
Related
I had used AddDays(x) method before on DateTime objects and it was working fine but now my object is defined like this:
public DateTime? To_Date { get; set; }
And looks like this one does not have a AddDays method. How can I call it then?
Because DateTime? can be in a state representing null, you need to consider what to do if it's null.
The most obvious thing to do is to stay with a value of null (the day after null is null).
DateTime? later = ToDate.HasValue
? To_Date.Value.AddDays(numberOfDays)
: (DateTime?)null;
It maybe that there's some meaningful default date you can use, in which case:
DateTime later = (ToDate ?? defaultDate).AddDays(numberOfDays);
This will use defaultDate when ToDate has no value, and the value of ToDate otherwise.
You need to do To_Date.Value.AddDays(1);
To_Date refers to the wrapper which only has a couple of properties. One is a flag to indicate whether or not it's null, the other is the value itself. First check that it's not null, try to use AddDays on the value.
Try this:
To_Date.Value.AddDays(x);
I am using Visual Studio and I want to convert the string I have in my textbox into the DateTime format. I am using the function Convert.ToDateTime() but the value that is returned is the min value (0/0/0001 00:00:00).
What is the problem?
The code where I retrieve the string from my textbox.
//pass startdate end date to studentResult.aspx
Session["startdate"] = txtStartDate.Text.ToString();
Session["enddate"] = txtEndDate.Text.ToString();
The code where I convert the string to datetime format.
string startdate = (string)(Session["startdate"]);
string enddate = (string)(Session["enddate"]);
DateTime one = Convert.ToDateTime(startdate);
DateTime two = Convert.ToDateTime(enddate);
As pointed in my comment, Convert.ToDateTime method returns DateTime.MinValue if the parameter is null.
Return Value
Type: System.DateTime
The date and time equivalent of the value of value, or the date and time equivalent of DateTime.MinValue if value is null.
Probably your parameter is null but since you didn't gave us more details, we can't know what the exact problem is.
As a comman mistake, make sure that you are passing as a parameter .Text property of your TextBox, not itself. See Squid's comment.
use try parse, it'll return false if any conversion error occurs
Datetime #dateTime;
if(DateTime.TryParse(txtStartDate.Text, out #dateTime)) {
return #dateTime;
}
I am aware of the standard procedure for displaying a DateTime in a custom format, like so:
MessageBox.Show(dateSent.ToString("dd/MM/yyyy hh:mm:ss"));
However, when I change the variable from a DateTime to a DateTime? to accept null values, I lose the definition for the ToString(string) overload. I need to use DateTime? as I am reading from a database which potentially has null values - if the field in the database has a null value, then I need to assign the variable a null value too.
So I have two questions:
1) Out of curiosity, does anyone know if there is a reason why DateTime? does not contain an overload for ToString(string)?
2) Could anyone suggest an alternative method for what I am trying to achieve?
DateTime? is syntactic sugar for Nullable<DateTime> and that's why it don't have ToString(format) overload.
However, you can access underlying DateTime struct using Value property. But before that use HasValue to check, if the value exists.
MessageBox.Show(dateSent.HasValue ? dateSent.Value.ToString("dd/MM/yyyy hh:mm:ss") : string.Empty)
Instead of having to manually perform a null check every time, you can write an extension method.
public static string ToStringFormat(this DateTime? dt, string format)
{
if(dt.HasValue)
return dt.Value.ToString(format);
else
return "";
}
And use it like this (with whatever string format you want)
Console.WriteLine(myNullableDateTime.ToStringFormat("dd/MM/yyyy hh:mm:ss"));
You can still use
variableName.Value.ToString(customFormat);
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 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