How to initialize a DateTime field?
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 some problems doing it.
In particular I am trying to inizialize these fields in this way:
mySmallVuln.Published = '1998,04,30';
mySmallVuln.LastUpdated = '2007,11,05';
But Visual Studio sign me it as error
Too many characters in character literal
What am I missing? How to solve it?
Solution 1:
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;
}
Solution 2:
DateTime d = default(DateTime);
The default keyword works for all data types too!
Solution 3:
Both are same....
1
mySmallVuln.Published = new DateTime(1998,04,30,0,0,0);
mySmallVuln.LastUpdated = new DateTime(2007,11,05,0,0,0);
2
mySmallVuln.Published = new DateTime(1998,04,30);
mySmallVuln.LastUpdated = new DateTime(2007,11,05);
in the first method you can assign hour minute and second respectively in parameter at the last three parameter.
Solution 4:
To initialize a DateTime
value you can use the DateTime
constructor:
mySmallVuln.Published = new DateTime(1998,04,30);
Solution 5:
You are using a character literal ''
which can only contain one character. If you want to use a string literal use ""
instead.
C# does not support DateTime
-literals as opposed to VB.NET (#4/30/1998#
).
Apart from that, a string is not a DateTime
. If you have a string you need to parse it to DateTime
first:
string published = "1998,04,30";
DateTime dtPublished = DateTime.ParseExact(published, "yyyy,MM,dd", CultureInfo.InvariantCulture);
mySmallVuln.Published = dtPublished;
or you can create a DateTime
via constructor:
DateTime dtPublished = new DateTime(1998, 04, 30);
or, since your string contains the year, month and day as strings, using String.Split
and int.Parse
:
string[] tokens = published.Split(',');
if (tokens.Length == 3 && tokens.All(t => t.All(Char.IsDigit)))
{
int year = int.Parse(tokens[0]);
int month = int.Parse(tokens[1]);
int day = int.Parse(tokens[2]);
dtPublished = new DateTime(year, month, day);
}