วิธี TimeSpan.FromSeconds() ใน C# ใช้เพื่อคืนค่า TimeSpan ที่แสดงจำนวนวินาทีที่ระบุ โดยที่ข้อมูลจำเพาะจะแม่นยำเป็นมิลลิวินาทีที่ใกล้ที่สุด
ไวยากรณ์
ไวยากรณ์มีดังนี้ -
public static TimeSpan FromSeconds (double val);
ด้านบน ค่าพารามิเตอร์คือจำนวนวินาที ซึ่งแม่นยำเป็นมิลลิวินาทีที่ใกล้ที่สุด
ตัวอย่าง
เรามาดูตัวอย่างกัน -
using System; public class Demo { public static void Main() { TimeSpan span1 = TimeSpan.FromSeconds(0.6768788); TimeSpan span2 = new TimeSpan(25, 15, 45); TimeSpan span3 = TimeSpan.FromHours(.4788); TimeSpan span4 = TimeSpan.FromMilliseconds(0.8787); TimeSpan span5 = TimeSpan.FromMinutes(2.550); Console.WriteLine("TimeSpan1 = "+span1); Console.WriteLine("TimeSpan2 = "+span2); Console.WriteLine("TimeSpan3 = "+span3); Console.WriteLine("TimeSpan4 = "+span4); Console.WriteLine("TimeSpan5 = "+span5); Console.WriteLine("Result (Comparison of span1 and span2) = "+TimeSpan.Compare(span1, span2)); Console.WriteLine("Result (Comparison of span2 and span3) = "+TimeSpan.Compare(span2, span3)); Console.WriteLine("Result (Comparison of span1 and span3) = "+TimeSpan.Compare(span1, span3)); Console.WriteLine("Result (Comparison of span3 and span4) = "+TimeSpan.Compare(span3, span4)); Console.WriteLine("Result (Comparison of span4 and span5) = "+TimeSpan.Compare(span4, span5)); } }
ผลลัพธ์
TimeSpan1 = 00:00:00.6770000 TimeSpan2 = 1.01:15:45 TimeSpan3 = 00:28:43.6800000 TimeSpan4 = 00:00:00.0010000 TimeSpan5 = 00:02:33 Result (Comparison of span1 and span2) = -1 Result (Comparison of span2 and span3) = 1 Result (Comparison of span1 and span3) = -1 Result (Comparison of span3 and span4) = 1 Result (Comparison of span4 and span5) = -1
ตัวอย่าง
using System; public class Demo { public static void Main() { TimeSpan span1 = TimeSpan.FromSeconds(1); TimeSpan span2 = new TimeSpan(-9, 45, 50); TimeSpan span3 = TimeSpan.FromHours(5); TimeSpan span4 = TimeSpan.FromMilliseconds(10000); TimeSpan span5 = TimeSpan.FromMinutes(2); Console.WriteLine("TimeSpan1 = "+span1); Console.WriteLine("TimeSpan2 = "+span2); Console.WriteLine("TimeSpan3 = "+span3); Console.WriteLine("TimeSpan4 = "+span4); Console.WriteLine("TimeSpan5 = "+span5); Console.WriteLine("Result (Comparison of span1 and span2) = "+TimeSpan.Compare(span1, span2)); Console.WriteLine("Result (Comparison of span2 and span3) = "+TimeSpan.Compare(span2, span3)); Console.WriteLine("Result (Comparison of span1 and span3) = "+TimeSpan.Compare(span1, span3)); Console.WriteLine("Result (Comparison of span3 and span4) = "+TimeSpan.Compare(span3, span4)); Console.WriteLine("Result (Comparison of span4 and span5) = "+TimeSpan.Compare(span4, span5)); } }
ผลลัพธ์
TimeSpan1 = 00:00:01 TimeSpan2 = -08:14:10 TimeSpan3 = 05:00:00 TimeSpan4 = 00:00:10 TimeSpan5 = 00:02:00 Result (Comparison of span1 and span2) = 1 Result (Comparison of span2 and span3) = -1 Result (Comparison of span1 and span3) = -1 Result (Comparison of span3 and span4) = 1 Result (Comparison of span4 and span5) = -1