Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

เมธอด DateTime.ToShortDateString() ใน C#

เมธอด DateTime.ToShortDateString() ใน C# ใช้สำหรับแปลงค่าของออบเจ็กต์ DateTime ปัจจุบันเป็นการแทนค่าสตริงวันที่สั้นเทียบเท่า

ไวยากรณ์

ไวยากรณ์มีดังนี้:

public string ToShortDateString ();

ตัวอย่าง

ตัวอย่างการใช้งานเมธอด DateTime.ToShortDateString():

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); 
    } 
}

ผลลัพธ์

โค้ดจะแสดงผลดังนี้:

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

ตัวอย่างเพิ่มเติม

ตัวอย่างที่สองกับ DateTime.Now และข้อมูลวัฒนธรรม:

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); 
    } 
}

ผลลัพธ์

โค้ดจะแสดงผลดังนี้ (ตัวอย่าง):

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

หมายเหตุ: รูปแบบวันที่สั้นขึ้นอยู่กับการตั้งค่าวัฒนธรรม (Culture) ของระบบ