w3resource logo


C# Sharp Programming Exercises

C# Sharp Exercises: Convert current DateTime object to local time

Secondary Nav

C# Sharp DateTime : Exercise-31 with Solution

Write a C# Sharp program to convert the value of the current DateTime object to local time.

Expected Output :

Enter a date and time.                                                  
1:57                                                                    
8/23/2016 1:57:00 AM local time is 8/22/2016 8:27:00 PM universal time. 
Enter a date and time in universal time.                                
8:27:00                                                                 
8/23/2016 8:27:00 AM universal time is 8/23/2016 1:57:00 PM local time.  

C# Sharp Code:

using System;

class Example31
{
	static void Main()
	{
		DateTime localDateTime, univDateTime;

		Console.WriteLine("Enter a date and time.");
		string strDateTime = Console.ReadLine();

		try {
			localDateTime = DateTime.Parse(strDateTime);
    		univDateTime = localDateTime.ToUniversalTime();

    		Console.WriteLine("{0} local time is {1} universal time.",
   								localDateTime,
    								univDateTime); 
		}
		catch (FormatException) {
			Console.WriteLine("Invalid format.");
			return;
		}

		Console.WriteLine("Enter a date and time in universal time.");
		strDateTime = Console.ReadLine();

		try {
			univDateTime = DateTime.Parse(strDateTime);
    		localDateTime = univDateTime.ToLocalTime();

    		Console.WriteLine("{0} universal time is {1} local time.",
    								 univDateTime,
    								 localDateTime); 
		}
		catch (FormatException) {
			Console.WriteLine("Invalid format.");
			return;
		}

	}
}

C# Sharp Practice online:

using System;

class Example31
{
	static void Main()
	{
		DateTime localDateTime, univDateTime;

		Console.WriteLine("Enter a date and time.");
		string strDateTime = Console.ReadLine();

		try {
			localDateTime = DateTime.Parse(strDateTime);
    		univDateTime = localDateTime.ToUniversalTime();

    		Console.WriteLine("{0} local time is {1} universal time.",
   								localDateTime,
    								univDateTime); 
		}
		catch (FormatException) {
			Console.WriteLine("Invalid format.");
			return;
		}

		Console.WriteLine("Enter a date and time in universal time.");
		strDateTime = Console.ReadLine();

		try {
			univDateTime = DateTime.Parse(strDateTime);
    		localDateTime = univDateTime.ToLocalTime();

    		Console.WriteLine("{0} universal time is {1} local time.",
    								 univDateTime,
    								 localDateTime); 
		}
		catch (FormatException) {
			Console.WriteLine("Invalid format.");
			return;
		}

	}
}

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:

PHP: Loop

JavaScript: Delete duplicates in an array

Oracle: Round the number