w3resource logo
C# Sharp Programming Exercises

C# Sharp Exercises: Converts current DateTime object to UTC

C# Sharp DateTime: Exercise-40 with Solution

Write a C# Sharp program to convert the value of the current DateTime object to Coordinated Universal Time (UTC).

Sample Solution:-

C# Sharp Code:

using System;

class Example40
{
	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;
		}

	}
}

Sample Output:

Enter a date and time.                                                                                        
06/12/2017 02:20                                                                                              
6/12/2017 2:20:00 AM local time is 6/11/2017 8:50:00 PM universal time.                                       
Enter a date and time in universal time.                                                                      
06/12/2017 2:30                                                                                               
6/12/2017 2:30:00 AM universal time is 6/12/2017 8:00:00 AM local time.

C# Sharp Code Editor:

using System;

class Example40
{
	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