Open In App

DateTime.ToString() Method in C# | Set – 1

Last Updated : 27 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

This method is used to Converts the value of the current DateTime object to its equivalent string representation. There are total 4 methods in the overload list of this method:
 

  • ToString(String, IFormatProvider)
  • ToString(String)
  • ToString(IFormatProvider)
  • ToString()

Here, we will discuss only first two methods.
 

ToString(String, IFormatProvider)

This method is used to convert the value of the current DateTime object to its equivalent string representation using the specified format and culture-specific format information.

Syntax: public string ToString (string format, IFormatProvider provider);
Parameters: 
format: A standard or custom date and time format string. 
provider: An object that supplies culture-specific formatting information.
Return Value: This method returns a string representation of the value of the current DateTime object as specified by format and provider. 

Exceptions: 

  • FormatException: If The length of format is 1, and it is not one of the format specifier characters defined for DateTimeFormatInfo or the format does not contain a valid custom format pattern.
  • ArgumentOutOfRangeException: If The date and time is outside the range of dates supported by the calendar used by provider.

Below programs illustrate the use of DateTime.ToString(String, IFormatProvider) Method:
Example 1:

csharp




// C# program to demonstrate the
// DateTime.ToString(String,
// IFormatProvider) Method
using System;
using System.Globalization;
 
class GFG {
 
    // Main Method
    public static void Main()
    {
        try {
 
            // creating object of CultureInfo
            CultureInfo cultures =
                CultureInfo.CreateSpecificCulture("de-DE");
 
            // declaring and initializing String array
            string[] format = {"d", "D", "f", "F", "g", "G",
                                   "m", "o", "r","s", "t" };
 
                                 
            // calling get() Method
            Console.WriteLine("Converts the value of the current"
                   + "DateTime object to its equivalent string");
 
            for (int j = 0; j < format.Length; j++)
            {
                get(format[j], cultures);
            }
        }
 
        catch (FormatException e)
        {
            Console.WriteLine("\n");
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
 
        catch (ArgumentOutOfRangeException e)
        {
            Console.WriteLine("\n");
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
 
    // Defining get() method
    public static void get(string format,
                    CultureInfo cultures)
    {
        // Define date to be displayed.
        DateTime dateToDisplay = new DateTime(2008, 10,
                                         1, 17, 4, 32);
 
        // converting DateTime to specified string
        string val = dateToDisplay.ToString(format, cultures);
 
        // display the converted ulong value
        Console.WriteLine(" {0} ", val);
    }
}


Output: 

Converts the value of the currentDateTime object to its equivalent string
 01.10.2008 
 Mittwoch, 1. Oktober 2008 
 Mittwoch, 1. Oktober 2008 17:04 
 Mittwoch, 1. Oktober 2008 17:04:32 
 01.10.2008 17:04 
 01.10.2008 17:04:32 
 1. Oktober 
 2008-10-01T17:04:32.0000000 
 Wed, 01 Oct 2008 17:04:32 GMT 
 2008-10-01T17:04:32 
 17:04

 

Example 2: For FormatException

csharp




// C# program to demonstrate the
// DateTime.ToString(String,
// IFormatProvider) Method
using System;
using System.Globalization;
 
class GFG {
 
    // Main Method
    public static void Main()
    {
        try {
 
            // creating object of CultureInfo
            CultureInfo cultures =
               CultureInfo.CreateSpecificCulture("de-DE");
 
            // declaring and initializing String array
            string[] format = {"d", "D", "f", "F", "g", "G",
                                                  "s", "x"};
 
            // calling get() Method
            Console.WriteLine("Converts the value of the current"
                   + "DateTime object to its equivalent string");
 
            for (int j = 0; j < format.Length; j++)
            {
                get(format[j], cultures);
            }
        }
 
        catch (FormatException e)
        {
            Console.WriteLine("\n");
            Console.WriteLine("format does not contain "+
                       "a valid custom format pattern.");
 
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
 
        catch (ArgumentOutOfRangeException e)
        {
            Console.WriteLine("\n");
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
 
    // Defining get() method
    public static void get(string format,
                    CultureInfo cultures)
    {
        // Define date to be displayed.
        DateTime dateToDisplay = new DateTime(2008,
                                 10, 1, 17, 4, 32);
 
        // converting DateTime to specified string
        string val = dateToDisplay.ToString(format, cultures);
 
        // display the converted ulong value
        Console.WriteLine(" {0} ", val);
    }
}


Output: 

Converts the value of the currentDateTime object to its equivalent string
 01.10.2008 
 Mittwoch, 1. Oktober 2008 
 Mittwoch, 1. Oktober 2008 17:04 
 Mittwoch, 1. Oktober 2008 17:04:32 
 01.10.2008 17:04 
 01.10.2008 17:04:32 
 2008-10-01T17:04:32 


format does not contain a valid custom format pattern.
Exception Thrown: System.FormatException

 

Example 3: For ArgumentOutOfRangeException

csharp




// C# program to demonstrate the
// DateTime.ToString(String,
// IFormatProvider) Method
using System;
using System.Globalization;
 
class GFG {
 
    // Main Method
    public static void Main()
    {
        try {
 
            // creating object of CultureInfo
            CultureInfo cultures =
              CultureInfo.CreateSpecificCulture("ar-SA");
 
            // declaring and initializing String array
            string[] format = {"d", "D", "f", "F",
                                   "g", "G","s" };
                                 
 
            // calling get() Method
            Console.WriteLine("Converts the value of the current"
                   + "DateTime object to its equivalent string");
 
            for (int j = 0; j < format.Length; j++) {
                get(format[j], cultures);
            }
        }
 
        catch (FormatException e)
        {
            Console.WriteLine("\n");
            Console.WriteLine("format does not contain "+
                       "a valid custom format pattern.");
 
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
 
        catch (ArgumentOutOfRangeException e)
        {
            Console.WriteLine("\n");
            Console.WriteLine("The date and time is outside the range of dates"
                                  + "supported by the calendar used by ar-SA");
 
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
 
    // Defining get() method
    public static void get(string format,
                    CultureInfo cultures)
    {
        // Define date to be displayed.
        DateTime dateToDisplay = new DateTime(2999,
                                 10, 1, 17, 4, 32);
 
        // converting DateTime to specified string
        string val = dateToDisplay.ToString(format, cultures);
 
        // display the converted ulong value
        Console.WriteLine(" {0} ", val);
    }
}


Output: 

Converts the value of the currentDateTime object to its equivalent string


The date and time is outside the range of datessupported by the calendar used by ar-SA
Exception Thrown: System.ArgumentOutOfRangeException

 

ToString(String) Method

This method is used to convert the value of the current DateTime object to its equivalent string representation using the specified format and the formatting conventions of the current culture.

Syntax: public string ToString (string format); 
Here it takes a standard or custom date and time format string.
Return Value: This method returns a string representation of value of the current DateTime object as specified by format.  

Exceptions: 

  • FormatException: If the length of format is 1, and it is not one of the format specifier characters defined for DateTimeFormatInfo or the format does not contain a valid custom format pattern.
  • ArgumentOutOfRangeException: If the date and time is outside the range of dates supported by the calendar used by the current culture.

Below programs illustrate the use of ToString(String) Method:
Example 1:

csharp




// C# program to demonstrate the
// DateTime.ToString(String) Method
using System;
using System.Globalization;
 
class GFG {
 
    // Main Method
    public static void Main()
    {
        try {
 
            // declaring and initializing String array
            string[] format = {"d", "D", "f", "F", "g",
                         "G", "m", "o", "r","s", "t" };
                                 
 
            // calling get() Method
            Console.WriteLine("Converts the value of the current"
                   + "DateTime object to its equivalent string");
 
            for (int j = 0; j < format.Length; j++)
            {
                get(format[j]);
            }
        }
 
        catch (FormatException e)
        {
            Console.WriteLine("\n");
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
 
        catch (ArgumentOutOfRangeException e)
        {
            Console.WriteLine("\n");
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
 
    // Defining get() method
    public static void get(string format)
    {
        // Define date to be displayed.
        DateTime dateToDisplay = new DateTime(2008,
                                 10, 1, 17, 4, 32);
 
        // converting DateTime to specified string
        string val = dateToDisplay.ToString(format);
 
        // display the converted ulong value
        Console.WriteLine(" {0} ", val);
    }
}


Output: 

Converts the value of the currentDateTime object to its equivalent string
 10/01/2008 
 Wednesday, 01 October 2008 
 Wednesday, 01 October 2008 17:04 
 Wednesday, 01 October 2008 17:04:32 
 10/01/2008 17:04 
 10/01/2008 17:04:32 
 October 01 
 2008-10-01T17:04:32.0000000 
 Wed, 01 Oct 2008 17:04:32 GMT 
 2008-10-01T17:04:32 
 17:04

 

Example 2: For FormatException

csharp




// C# program to demonstrate the
// DateTime.ToString(String) Method
using System;
using System.Globalization;
 
class GFG {
 
    // Main Method
    public static void Main()
    {
        try {
 
            // declaring and initializing String array
            string[] format = {"d", "D", "f", "F",
                              "g", "G", "s", "x" };
                                 
 
            // calling get() Method
            Console.WriteLine("Converts the value of the current"
                   + "DateTime object to its equivalent string");
 
            for (int j = 0; j < format.Length; j++)
            {
                get(format[j]);
            }
        }
 
        catch (FormatException e)
        {
            Console.WriteLine("\n");
            Console.WriteLine("format does not contain "+
                        "a valid custom format pattern.");
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
 
        catch (ArgumentOutOfRangeException e)
        {
            Console.WriteLine("\n");
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
 
    // Defining get() method
    public static void get(string format)
    {
        // Define date to be displayed.
        DateTime dateToDisplay = new DateTime(2008,
                                 10, 1, 17, 4, 32);
 
        // converting DateTime to specified string
        string val = dateToDisplay.ToString(format);
 
        // display the converted ulong value
        Console.WriteLine(" {0} ", val);
    }
}


Output: 

Converts the value of the currentDateTime object to its equivalent string
 10/01/2008 
 Wednesday, 01 October 2008 
 Wednesday, 01 October 2008 17:04 
 Wednesday, 01 October 2008 17:04:32 
 10/01/2008 17:04 
 10/01/2008 17:04:32 
 2008-10-01T17:04:32 


format does not contain a valid custom format pattern.
Exception Thrown: System.FormatException

 

Example 3: For ArgumentOutOfRangeException

csharp




// C# program to demonstrate the
// DateTime.ToString(String) Method
using System;
using System.Globalization;
 
class GFG {
 
    // Main Method
    public static void Main()
    {
        try {
 
            // declaring and initializing String array
            string[] format = {"d", "D", "f", "F",
                                   "g", "G","s" };
                                 
 
            // calling get() Method
            Console.WriteLine("Converts the value of the current"
                   + "DateTime object to its equivalent string");
 
            for (int j = 0; j < format.Length; j++)
            {
                get(format[j]);
            }
        }
 
        catch (FormatException e)
        {
            Console.WriteLine("\n");
            Console.WriteLine("format does not contain "+
                       "a valid custom format pattern.");
 
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
 
        catch (ArgumentOutOfRangeException e)
        {
            Console.WriteLine("\n");
            Console.WriteLine("The date and time are outside the range of dates "
                     + "supported by the calendar used by the current culture.");
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
 
    // Defining get() method
    public static void get(string format)
    {
        // Define date to be displayed.
        DateTime dateToDisplay = new DateTime(9999,
                                 13, 1, 17, 4, 32);
 
        // converting DateTime to specified string
        string val = dateToDisplay.ToString(format);
 
        // display the converted ulong value
        Console.WriteLine(" {0} ", val);
    }
}


Output:
Converts the value of the currentDateTime object to its equivalent string
The date and time are outside the range of dates supported by the calendar used by the current culture. 
Exception Thrown: System.ArgumentOutOfRangeException 
 

Reference: 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads