How to initialize a DateTime field?

前端 未结 9 1247
Happy的楠姐
Happy的楠姐 2020-12-06 04:01

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

9条回答
  •  被撕碎了的回忆
    2020-12-06 04:51

    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);
    }
    

提交回复
热议问题