How can I format a nullable DateTime with ToString()?

前端 未结 20 2461
面向向阳花
面向向阳花 2020-11-27 12:04

How can I convert the nullable DateTime dt2 to a formatted string?

DateTime dt = DateTime.Now;
Console.WriteLine(dt.ToString(\"yyyy-MM-dd hh         


        
20条回答
  •  野性不改
    2020-11-27 12:29

    Shortest answer

    $"{dt:yyyy-MM-dd hh:mm:ss}"
    

    Tests

    DateTime dt1 = DateTime.Now;
    Console.Write("Test 1: ");
    Console.WriteLine($"{dt1:yyyy-MM-dd hh:mm:ss}"); //works
    
    DateTime? dt2 = DateTime.Now;
    Console.Write("Test 2: ");
    Console.WriteLine($"{dt2:yyyy-MM-dd hh:mm:ss}"); //Works
    
    DateTime? dt3 = null;
    Console.Write("Test 3: ");
    Console.WriteLine($"{dt3:yyyy-MM-dd hh:mm:ss}"); //Works - Returns empty string
    
    Output
    Test 1: 2017-08-03 12:38:57
    Test 2: 2017-08-03 12:38:57
    Test 3: 
    

提交回复
热议问题