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

DateTime.ToString() วิธีการใน C #


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

ไวยากรณ์

ต่อไปนี้เป็นไวยากรณ์ -

ToString(String, IFormatProvider)
ToString()
ToString(IFormatProvider)
ToString(String)

ตัวอย่าง

ให้เรามาดูตัวอย่างการใช้งาน DateTime.ToString() method −

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.ToString();
      Console.WriteLine("String representation = {0}", str);
   }
}

ผลลัพธ์

สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -

Date = 11/11/2019 7:11:25 AM
String representation = 11/11/2019 7:11:25 AM

ตัวอย่าง

ให้เราดูตัวอย่างอื่นเพื่อใช้เมธอด DateTime.ToString(String) -

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.ToString("f");
      Console.WriteLine("String representation = {0}", str);
   }
}

ผลลัพธ์

สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -

Date = 11/11/2019 7:11:25 AM
String representation = Monday, November 11, 2019 7:11 AM