I am absolutly new in C# (I came from Java) and I have a very stupid problem
I have to initialize some DateTime fields into an object but I have som
DateTime d = default(DateTime);
The default keyword works for all data types too!
use this
// year,month,day
mySmallVuln.Published=new DateTime(2011,11,4);
To initialize a DateTime
value you can use the DateTime
constructor:
mySmallVuln.Published = new DateTime(1998,04,30);
You can either parse a string, like yours. Or you can instansiate a DateTime object with numbers.
DateTime date1 = new DateTime(1998, 04, 30);
DateTime date2 = DateTime.ParseExact("1998,04,30", "yyyy,MM,dd", CultureInfo.InvariantCulture);
Unfortunately, C# does not support Date literals. You should change your code and instantiate the DateTime objects using new DateTime(..)
, as thomas exemplified in his answer.
Just for the sake of expanding on this topic: VB.NET supports date literals using the # character (ironically). This is how they can be expressed, from the MSDN documentation:
Dim d As Date
d = # 8/23/1970 3:45:39AM #
d = # 8/23/1970 # ' Date value: 8/23/1970 12:00:00AM.
d = # 3:45:39AM # ' Date value: 1/1/1 3:45:39AM.
d = # 3:45:39 # ' Date value: 1/1/1 3:45:39AM.
d = # 13:45:39 # ' Date value: 1/1/1 1:45:39PM.
d = # 1AM # ' Date value: 1/1/1 1:00:00AM.
d = # 13:45:39PM # ' This date value is not valid.
mySmallVuln.Published = new DateTime(1998,04,30);
Or perhaps like this
var date = DateTime.MinValue;
if (DateTime.TryParse("1998/04/30", out date))
{
//Sucess...
mySmallVuln.Published = date;
}