How to initialize a DateTime field?

前端 未结 9 1233
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:40
     DateTime d = default(DateTime);
    

    The default keyword works for all data types too!

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

    use this

    // year,month,day

    mySmallVuln.Published=new DateTime(2011,11,4);
    
    0 讨论(0)
  • 2020-12-06 04:43

    To initialize a DateTime value you can use the DateTime constructor:

    mySmallVuln.Published = new DateTime(1998,04,30);
    
    0 讨论(0)
  • 2020-12-06 04:43

    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);
    
    0 讨论(0)
  • 2020-12-06 04:44

    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.
    
    0 讨论(0)
  • 2020-12-06 04:48
    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;
    }
    
    0 讨论(0)
提交回复
热议问题