w3resource logo


C# Sharp Programming Exercises

C# Sharp Exercises: Add a number of whole and fractional values to a date and time


C# Sharp DateTime : Exercise-11 with Solution

Write C# Sharp program to add a number of whole and fractional values to a date and time.

Expected Output :

8/16/2016 12:00:00 PM + 0.08333 hour(s) = 8/16/2016 12:04:59 PM         
8/16/2016 12:00:00 PM + 0.16667 hour(s) = 8/16/2016 12:10:00 PM         
8/16/2016 12:00:00 PM + 0.25 hour(s) = 8/16/2016 12:15:00 PM            
8/16/2016 12:00:00 PM + 0.33333 hour(s) = 8/16/2016 12:19:59 PM         
8/16/2016 12:00:00 PM + 0.5 hour(s) = 8/16/2016 12:30:00 PM             
8/16/2016 12:00:00 PM + 0.66667 hour(s) = 8/16/2016 12:40:00 PM         
8/16/2016 12:00:00 PM + 1 hour(s) = 8/16/2016 1:00:00 PM                
8/16/2016 12:00:00 PM + 2 hour(s) = 8/16/2016 2:00:00 PM                
8/16/2016 12:00:00 PM + 29 hour(s) = 8/17/2016 5:00:00 PM               
8/16/2016 12:00:00 PM + 30 hour(s) = 8/17/2016 6:00:00 PM               
8/16/2016 12:00:00 PM + 31 hour(s) = 8/17/2016 7:00:00 PM               
8/16/2016 12:00:00 PM + 90 hour(s) = 8/20/2016 6:00:00 AM               
8/16/2016 12:00:00 PM + 365 hour(s) = 8/31/2016 5:00:00 PM   

C# Sharp Code:

using System;
public class Example11
{
   public static void Main()
   {
      double[] hours = {.08333, .16667, .25, .33333, .5, .66667, 1, 2, 
                        29, 30, 31, 90, 365};
      DateTime dateValue = new DateTime(2016, 8, 16, 12, 0, 0);

      foreach (double hour in hours)
         Console.WriteLine("{0} + {1} hour(s) = {2}", dateValue, hour, 
                           dateValue.AddHours(hour));

   }
}

C# Sharp Practice online:

using System;
public class Example11
{
   public static void Main()
   {
      double[] hours = {.08333, .16667, .25, .33333, .5, .66667, 1, 2, 
                        29, 30, 31, 90, 365};
      DateTime dateValue = new DateTime(2016, 8, 16, 12, 0, 0);

      foreach (double hour in hours)
         Console.WriteLine("{0} + {1} hour(s) = {2}", dateValue, hour, 
                           dateValue.AddHours(hour));

   }
}

Improve this sample solution and post your code through Disqus.



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

Help the community:

Python: Fizzbuzz

C++: Decimal to binary conversion

JavaScript: Need Help in JavaScript

Python: Help me with this program