w3resource logo


C# Sharp Programming Exercises

C# Sharp Exercises: Time of day from a given array of date time values


C# Sharp DateTime : Exercise-7 with Solution

Write a C# Sharp program to get the time of day from a given array of date time values.

Array of DateTime : 
    DateTime[] dates = { DateTime.Now, 
                           new DateTime(2016, 8, 16, 9, 28, 0),
                           new DateTime(2011, 5, 28, 10, 35, 0),
                           new DateTime(1979, 12, 25, 14, 30, 0) };

Expected Output :

Day: 8/20/2016 Time: 15:58:26.3566320                                   
Day: 8/20/2016 Time: 3:58 PM                                            
                                                                        
Day: 8/16/2016 Time: 09:28:00                                           
Day: 8/16/2016 Time: 9:28 AM                                            
                                                                        
Day: 5/28/2011 Time: 10:35:00                                           
Day: 5/28/2011 Time: 10:35 AM                                           
                                                                        
Day: 12/25/1979 Time: 14:30:00                                          
Day: 12/25/1979 Time: 2:30 PM

C# Sharp Code:

using System;
public class Example7
{
   public static void Main()
   {
      DateTime[] dates = { DateTime.Now, 
                           new DateTime(2016, 8, 16, 9, 28, 0),
                           new DateTime(2011, 5, 28, 10, 35, 0),
                           new DateTime(1979, 12, 25, 14, 30, 0) };
      foreach (var date in dates) {
         Console.WriteLine("Day: {0:d} Time: {1:g}", date.Date, date.TimeOfDay);
         Console.WriteLine("Day: {0:d} Time: {0:t}\n", date);
      }                              
   }
}

C# Sharp Practice online:

using System;
public class Example7
{
   public static void Main()
   {
      DateTime[] dates = { DateTime.Now, 
                           new DateTime(2016, 8, 16, 9, 28, 0),
                           new DateTime(2011, 5, 28, 10, 35, 0),
                           new DateTime(1979, 12, 25, 14, 30, 0) };
      foreach (var date in dates) {
         Console.WriteLine("Day: {0:d} Time: {1:g}", date.Date, date.TimeOfDay);
         Console.WriteLine("Day: {0:d} Time: {0:t}\n", date);
      }                              
   }
}

Improve this sample solution and post your code through Disqus.



Join our Question Answer community to learn and share your programming knowledge.