Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Phương thức DateTime.ToString() trong C#

Phương thức DateTime.ToString() trong C# được dùng để chuyển đổi giá trị của đối tượng DateTime hiện tại thành biểu diễn chuỗi tương đương. Phương thức này có nhiều nạp chồng để hỗ trợ các định dạng khác nhau.

Cú pháp

Các nạp chồng phổ biến:

ToString()
ToString(String format)
ToString(IFormatProvider provider)
ToString(String format, IFormatProvider provider)

Ví dụ 1 - ToString() mặc định

using System;

public class Demo
{
    public static void Main()
    {
        DateTime d = new DateTime(2019, 11, 11, 7, 11, 25);
        Console.WriteLine("Date = {0}", d);
        string str = d.ToString();
        Console.WriteLine("String representation = {0}", str);
    }
}

Kết quả

Date = 11/11/2019 7:11:25 AM
String representation = 11/11/2019 7:11:25 AM

Ví dụ 2 - ToString(String) với định dạng "f"

using System;

public class Demo
{
    public static void Main()
    {
        DateTime d = new DateTime(2019, 11, 11, 7, 11, 25);
        Console.WriteLine("Date = {0}", d);
        string str = d.ToString("f");
        Console.WriteLine("String representation = {0}", str);
    }
}

Kết quả

Date = 11/11/2019 7:11:25 AM
String representation = Monday, November 11, 2019 7:11 AM