Reputation: 256
I want to use object
type as a parameter in order to get value from various type (int,string,datetime
,etc) and return the string representation of the object.
But I have a problem with DateTime
. I know that object
is a parent class of DateTime
so there won't have any method of it child class.
So is there any way to copy some value from object
and instantiate a new DateTime
object
or there is any other method.
public static string getStringOfValue(object value)
{
// all of this List is used for type checking //////////////
List<object> _number_type_list = new List<object>()
{
typeof(byte), typeof(sbyte), typeof(int), typeof(long),
typeof(short), typeof(ushort), typeof(uint), typeof(ulong),
typeof(float), typeof(float), typeof(decimal)
};
List<object> _string_type_list = new List<object>()
{
typeof(char),typeof(string)
};
List<object> _boolean_type_list = new List<object>()
{
typeof(bool)
};
//////////////////////////////////////////////////
// used for format string of DateTime
string SQL_DATETIME_FORMAT = "YYYYMMdd hhmmss.fff";
var value_type = value.GetType();
var value_string = "";
if (_number_type_list.Contains(value_type) || _boolean_type_list.Contains(value_type))
{
value_string = value.ToString();
}
else if (_string_type_list.Contains(value_type))
{
value_string = "'" + value + "'";
}
else if (value.GetType() == typeof(System.DateTime))
{
//// how can I use format string method of DateTime ////
value_string = value.ToString();
// value_string = value.ToString(SQL_DATETIME_FORMAT);
////////////////////////////////////////////////////////
}
return value_string;
}
Upvotes: 1
Views: 83
Reputation: 726709
how can I use format string method of
DateTime
Cast your value
to DateTime
before making the call:
value_string = ((DateTime)value).ToString(SQL_DATETIME_FORMAT);
Upvotes: 1