I've made a method to convert a datetime object to a date-only format. In order to access it, I have to assign the value of my parameter to the value that will be in a datatable. The obvious method would thus be to add a ? after the DateTime object to make it nullable, however this removes it's methods (or at least, the one I need to use), making my method worthless.
string dateWithOutTime(DateTime? datetime)
{
string reply = datetime.Date.ToString();
return reply;
}
usage:
string str = dateWithOutTime(*DataSet*.*DataTable[n]*.Rows[n][n] as DateTime?);
Is there a way to accomplish this without adding any extra objects?
Note: a star (*) denotes a variable type/object
DateTime? doesn't have the same methods as DateTime, they're different types. You have to retrieve the actual datetime value using DateTime?'s Value property:
string dateWithOutTime(DateTime? datetime)
{
if(datetime.HasValue)
return datetime.Value.Date.ToString();
else
return //...
}
Read the documentation for Nullable<T> here.
Unless I misunderstand your problem, I'd say you need to check if your DateTime? parameter is null or not. If it is, return an empty string (or a string you want to display for missing dates). If it isn't, you can use the Value property:
string dateWithOutTime(DateTime? datetime)
{
return datetime.HasValue ? datetime.Value.Date.ToString() : String.Empty;
}
Update
If you only want the date-part in your string and you want it to be culture-sensitive, you can use ToShortDateString() instead of ToString(). You can even leave out the Date property:
string dateWithOutTime(DateTime? datetime)
{
return datetime.HasValue
? datetime.Value.ToShortDateString()
: String.Empty;
}
Related
I am trying to convert a DateTime and an int property into a string in a foreach loop. I need to put the information that is stored in the objects properties into the variables and then use that info to write to a text file using StreamWriter. I'm not quite sure what I am doing wrong. Parse is red underlined with this error message -
Error 2 'string' does not contain a definition for 'Parse'
Here is my code -
public bool Save()
{
string appointStart;
string appointLength;
string appointDescription;
foreach (Appointment appointment in appointments)
{
appointStart = string.Parse(appointment.Start);
appointLength = string.Parse(appointment.Length);
appointDescription = appointment.DisplayableDescription;
}
return true;
}
Thank you
Use the ToString() methods of DateTime and Int32 class to get a string representation of the specified types. Some ToString() methods provide overloads to define the formatting of the string value.
foreach (Appointment appointment in appointments)
{
appointStart = appointment.Start.ToString();
appointLength = appointment.Length.ToString();
appointDescription = appointment.DisplayableDescription;
}
Why do you need to Parse the DateTime and int into String?? Because if you just want to have the variables in string format, you can simply use .ToString() or Convert.Tostring()
while am trying to convert the return value of add method to string it is not returning any value in console.while i remove the tostring method it is returning value.if i write any character inside the double quote it is showing in console.
what is happening while am calling tostring method?
if i didn't put any double quote as parameter it is showing compile time error like (specify culture of string)
what is the purpose of specifying culture while converting int to string?
i think i can convert integer value to string by calling tostring method,why can't i do conversion in this scenario?
private static int Add(int x,int y)
{
return x+y;
}
static void Main(string[] args)
{
Console.WriteLine(Add(23,54).ToString(""));
Console.ReadKey();
}
thanks.
It's all about implementation;
From Int32.ToString(string)
If format is null or an empty string (""), the return value of this
instance is formatted with the general numeric format specifier ("G").
That's why .ToString("") is equal to .ToString() because
From Int32.ToString()
The ToString() method formats an Int32 value in the default ("G", or
general) format by using the NumberFormatInfo object of the current
culture.
I tried all cultures to format with .ToString("") and no culture returns null or empty string.
foreach (var c in CultureInfo.GetCultures(CultureTypes.AllCultures))
{
if((77).ToString("G", c) != "77")
Console.WriteLine (c.Name);
}
Blue line probably there is a plugin (maybe ReSharper) that warn you to use another overloads that takes CultureInfo as a parameter for example.
Use ToString with no parameters
Add(23,54).ToString()
Using the parameter you specified you set a culture for the string conversion.
More here.
simply specify your culture of string as string.empty
Console.WriteLine(Add(23,54).ToString(string.Empty));
Console.ReadKey();
Culture Name:"" (empty string)
Culture Identifier:0x007F
Language-Country/Region:invariant culture
http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo%28v=vs.71%29.aspx
string.Empty is a read-only field whereas "" is a compile time constant.some Places they behave differently.
I use the below code
extensionRequest[i].EndDate = DateTime.Parse(dsResult.Tables[0].Rows[i]["ActualEndDate"].ToString());
extensionRequest[i].ExtendedEndDate = DateTime.Parse(dsResult.Tables[0].Rows[i]["ExtendedEndDate"].ToString());
extensionRequest[i].ReceivedDate =Convert.ToDateTime(dsResult.Tables[0].Rows[i]["dReceivedOn"].ToString());
this works fine when values are coming from the DB
but when NULL values are returned it throws an exception!!
Should i check values for all three values like the code below
if (dsResult.Tables[0].Rows[i]["dReceivedOn"].ToString()==null){
extensionRequest[i].ReceivedDate="";
}
else{
extensionRequest[i].ReceivedDate =Convert.ToDateTime(dsResult.Tables[0].Rows[i]["dReceivedOn"].ToString());
}
or i should assign all dates to null on exception?!
is there any other way to do in single line? like tryparse or something?
I'll try being creative. You can create a Nullable TryParse as an Extension Method edition:
public static DateTime? TryParseNullable(this DateTime dateTime, string val)
{
DateTime outValue;
return DateTime.TryParse(val, out outValue) ? (DateTime?) outValue : null;
}
and then use:
extensionRequest[i].EndDate = DateTime.TryParseNullable(dsResult.Tables[0].Rows[i]["ActualEndDate"].ToString());
and that can be your one liner.
You can use DateTime.TryParse() method which returns true on successfull conversion otherwise returns false.
Note: calling ToString() on null throw NullReferenceException hence you need to check for null value before conversion.
Try This:
if(dsResult.Tables[0].Rows[i]["ActualEndDate"] != null)
DateTime.TryParse(dsResult.Tables[0].Rows[i]["ActualEndDate"].ToString(),
out extensionRequest[i].EndDate);
You can check if value is null like this
extensionRequest[i].EndDate = Convert.IsDbNull(dsResult.Tables[0].Rows[i]["ActualEndDate"]) ? null : Convert.ToDateTime(dsResult.Tables[0].Rows[i]["ActualEndDate"]);
I'm sure .ToString() is not required.
It will be more readable if you cache a row to the local variable:
var row = dsResult.Tables[0].Rows[i];
...
extensionRequest[i].EndDate = Convert.IsDbNull(row["ActualEndDate"]) ? null : Convert.ToDateTime(row["ActualEndDate"]);
Be sure .EndDate and others allow null values. In other words, that is DateTime?
can i override Convert.ToDateTime()? I don't want 100 times or more check if string is nul and if is not then convert it to DateTime. Can i override this function to check if is null then will return null otherway convert it.
No, you can't override static methods. But you can write your own static method:
// TODO: Think of a better class name - this one sucks :)
public static class MoreConvert
{
public static DateTime? ToDateTimeOrNull(string text)
{
return text == null ? (DateTime?) null : Convert.ToDateTime(text);
}
}
Note that the return type has to be DateTime? because DateTime itself is a non-nullable value type.
You might also want to consider using DateTime.ParseExact instead of Convert.ToDateTime - I've never been terribly fond of its lenient, current-culture-specific behaviour. It depends where the data is coming from though. Do you know the format? Is it going to be in the user's culture, or the invariant culture? (Basically, is it user-entered text, or some machine-generated format?)
ToDateTime can't be overriden but you can use TryParse:
bool valid = DateTime.TryParse("date string", out d);
You can use DateTime.Parse instead, if you are sure that your string is in correct format.
private string? typeOfContract
{
get { return (string?)ViewState["typeOfContract"]; }
set { ViewState["typeOfContract"] = value; }
}
Later in the code I use it like this:
typeOfContract = Request.QueryString["type"];
I am getting the following error at the declaration of typeOfContract line stating:
The type 'string' must be a non-nullable value type in order to use
it as parameter 'T' in the generic type or method
'System.Nullable<T>'
Any ideas? Basically, I want to make sure that "type" exists in the QueryString before performing an action.
System.String is a reference type and already "nullable".
Nullable<T> and the ? suffix are for value types such as Int32, Double, DateTime, etc.
You are making it complicated. string is already nullable. You don't need to make it more nullable. Take out the ? on the property type.
string cannot be the parameter to Nullable because string is not a value type. String is a reference type.
string s = null;
is a very valid statement and there is not need to make it nullable.
private string typeOfContract
{
get { return ViewState["typeOfContract"] as string; }
set { ViewState["typeOfContract"] = value; }
}
should work because of the as keyword.
String is a reference type, so you don't need to (and cannot) use Nullable<T> here. Just declare typeOfContract as string and simply check for null after getting it from the query string. Or use String.IsNullOrEmpty if you want to handle empty string values the same as null.
For nullable, use ? with all of the C# primitives, except for string.
The following page gives a list of the C# primitives:
http://msdn.microsoft.com/en-us/library/aa711900(v=vs.71).aspx