How to initialize a DateTime field?

前端 未结 9 1234
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);
    }
    
    0 讨论(0)
  • 2020-12-06 04:59

    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.

    0 讨论(0)
  • 2020-12-06 05:04

    If you search for the error you get, you'll find:

    This is because, in C#, single quotes ('') denote (or encapsulate) a single character, whereas double quotes ("") are used for a string of characters.

    So you'll try:

    DateTime foo = "2014,02,20";
    

    Which yields:

    Cannot implicitly convert type 'string' to 'System.DateTime'

    Now if you search for that error, you'll find:

    int StartYear = 2012;
    int StartMonth = 06;
    int StartDay = 15;
    
    DateTime dt = new DateTime(StartYear, StartMonth, StartDay);
    
    0 讨论(0)
提交回复
热议问题