📜  C#中的DateTime.ToString()方法|套装– 1

📅  最后修改于: 2021-05-29 17:21:13             🧑  作者: Mango

此方法用于将当前DateTime对象的值转换为其等效的字符串表示形式。此方法的重载列表中共有4种方法:

  • ToString(String,IFormatProvider)
  • ToString(字符串)
  • ToString(IFormatProvider)
  • ToString()

在这里,我们将只讨论前两种方法。

ToString(String,IFormatProvider)

此方法用于使用指定的格式和区域性特定的格式信息将当前DateTime对象的值转换为其等效的字符串表示形式。

例外情况:

  • FormatException:如果format的长度为1,并且不是为DateTimeFormatInfo定义的格式说明字符之一,或者该格式不包含有效的自定义格式模式。
  • ArgumentOutOfRangeException:如果日期和时间超出提供者使用的日历支持的日期范围。

下面的程序说明了DateTime.ToString(String,IFormatProvider)方法的用法:

范例1:

// 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 intializing 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);
    }
}
输出:
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

示例2:对于FormatException

// 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 intializing 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);
    }
}
输出:
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

示例3:对于ArgumentOutOfRangeException

// 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 intializing 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);
    }
}
输出:
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)方法

此方法用于使用指定的格式和当前区域性的格式约定将当前DateTime对象的值转换为其等效的字符串表示形式。

例外情况:

  • FormatException:如果format的长度为1,并且不是为DateTimeFormatInfo定义的格式说明字符之一,或者该格式不包含有效的自定义格式模式。
  • ArgumentOutOfRangeException:如果日期和时间超出当前区域性使用的日历支持的日期范围。

下面的程序说明了ToString(String)方法的用法:

范例1:

// 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 intializing 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);
    }
}
输出:
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

示例2:对于FormatException

// 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 intializing 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);
    }
}
输出:
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

示例3:对于ArgumentOutOfRangeException

// 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 intializing 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);
    }
}
输出:

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.datetime.tostring?view=netframework-4.7.2