เมธอด DateTime.ToShortTimeString() ใน C# ใช้สำหรับแปลงค่าของออบเจ็กต์ DateTime ปัจจุบันเป็นการแทนค่าสตริงเวลาสั้นเทียบเท่า
ไวยากรณ์
ไวยากรณ์มีดังนี้:
public string ToShortTimeString ();
ตัวอย่าง
ตัวอย่างการใช้งานเมธอด DateTime.ToShortTimeString() พร้อมข้อมูลวัฒนธรรม:
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.ToShortTimeString();
Console.WriteLine("Short time string = {0}", pattern.ShortTimePattern);
Console.WriteLine("Short time string representation = {0}", str);
}
}
ผลลัพธ์
โค้ดจะแสดงผลดังนี้ (ตัวอย่าง):
Date = 10/16/2019 8:59:23 AM Current culture = en-US Short time string = h:mm tt Short time string representation = 8:59 AM
ตัวอย่างเพิ่มเติม
ตัวอย่างที่สองกับวันที่เฉพาะเจาะจง:
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.ToShortTimeString();
Console.WriteLine("Short time string representation = {0}", str);
}
}
ผลลัพธ์
โค้ดจะแสดงผลดังนี้:
Date = 11/11/2019 7:11:25 AM Short time string representation = 7:11 AM
หมายเหตุ: รูปแบบเวลาสั้นขึ้นอยู่กับการตั้งค่าวัฒนธรรม (Culture) ของระบบ