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

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

Phương thức DateTime.ToLongTimeString() trong C# chuyển đổi giá trị của đối tượng DateTime hiện tại thành biểu diễn chuỗi thời gian dài (long time string) tương đương.

Cú pháp

public string ToLongTimeString();

Ví dụ 1: Sử dụng DateTime.Now

using System;
using System.Globalization;
public class Demo {
    public static void Main() {
        DateTime d = DateTime.Now;
        Console.WriteLine("Ngày = {0}", d);
        Console.WriteLine("Culture hiện tại = " + CultureInfo.CurrentCulture.Name);
        var pattern = CultureInfo.CurrentCulture.DateTimeFormat;
        string str = d.ToLongTimeString();
        Console.WriteLine("Mẫu thời gian dài = {0}", pattern.LongTimePattern);
        Console.WriteLine("Biểu diễn thời gian dài = {0}", str);
    }
}

Kết quả

Ngày = 10/16/2019 8:41:03 AM
Culture hiện tại = en-US
Mẫu thời gian dài = h:mm:ss tt
Biểu diễn thời gian dài = 8:41:03 AM

Ví dụ 2: Với DateTime xác định

using System;
public class Demo {
    public static void Main() {
        DateTime d = new DateTime(2019, 11, 11, 7, 11, 25);
        Console.WriteLine("Ngày = {0}", d);
        string str = d.ToLongTimeString();
        Console.WriteLine("Biểu diễn thời gian dài = {0}", str);
    }
}

Kết quả

Ngày = 11/11/2019 7:11:25 AM
Biểu diễn thời gian dài = 7:11:25 AM