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

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

Phương thức DateTime.ToShortDateString() 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 ngày ngắn.

Cú pháp

Cú pháp như sau:

public string ToShortDateString();

Ví dụ 1 - DateTime cụ thể

using System;

public class Demo
{
    public static void Main()
    {
        DateTime d = new DateTime(2019, 08, 11, 9, 10, 45);
        Console.WriteLine("Date = {0}", d);
        string str = d.ToShortDateString();
        Console.WriteLine("Short date string representation = {0}", str);
    }
}

Kết quả

Date = 8/11/2019 9:10:45 AM
Short date string representation = 8/11/2019

Ví dụ 2 - DateTime.Now với CultureInfo

using System;
using System.Globalization;

public class Demo
{
    public static void Main()
    {
        DateTime d = DateTime.Now;
        Console.WriteLine("Date = {0}", d);
        Console.WriteLine("Current culture = " + CultureInfo.CurrentCulture.Name);
        var pattern = CultureInfo.CurrentCulture.DateTimeFormat;
        string str = d.ToShortDateString();
        Console.WriteLine("Short date string = {0}", pattern.ShortDatePattern);
        Console.WriteLine("Short date string representation = {0}", str);
    }
}

Kết quả

Date = 10/16/2019 8:56:40 AM
Current culture = en-US
Short date string = M/d/yyyy
Short date string representation = 10/16/2019