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

ตัวกำหนดรูปแบบวันที่ทั่วไป เวลาสั้น (g) ใน C#

ตัวกำหนดรูปแบบ General Date Short Time เป็นการรวมของรูปแบบวันที่สั้น ("d") และเวลาสั้น ("t") คั่นด้วยช่องว่าง

กำหนดวันที่โดยใช้ DateTime:

DateTime dt = new DateTime(2018, 10, 2, 7, 59, 20);

ตอนนี้ ให้ใช้ตัวกำหนดรูปแบบ ("g"):

dt.ToString("g", DateTimeFormatInfo.InvariantInfo));

ตัวอย่าง

using System;
using System.Globalization;

class Demo
{
    static void Main()
    {
        DateTime dt = new DateTime(2018, 10, 2, 7, 59, 20);
        Console.WriteLine(dt.ToString("g", DateTimeFormatInfo.InvariantInfo));
        Console.WriteLine(dt.ToString("g", CultureInfo.CreateSpecificCulture("en-us")));
    }
}

ผลลัพธ์

10/02/2018 07:59
10/2/2018 7:59 AM