From: 011netservice@gmail.com Date: 2023-05-15 Subject: DateTime.txt 章節 #### Round-trip Date and time values 歡迎來信交流, 訂購軟體需求. 以下 #### 標記段落, **** 標記常用(流程、設定、備忘) #### Round-trip Date and time values The "O" or "o" format preserves time zone information. Round-trip means the formatted string can be parsed back to a date time value. The "O" or "o" standard format specifier corresponds to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK" custom format string for DateTime values and to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffzzz" custom format string for DateTimeOffset values. 大寫"O", Round-trip, "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK". 小寫"o", Round-trip, "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffzzz", 例如: 2008-06-12T18:45:15.0000000-05:00 □ Round-trip a DateTime value const string fileName = @".\DateFile.txt"; StreamWriter outFile = new StreamWriter(fileName); // Save DateTime value. // 本地時間 DateTime dateToSave = DateTime.SpecifyKind(new DateTime(2008, 6, 12, 18, 45, 15), DateTimeKind.Local); string? dateString = dateToSave.ToString("o"); Console.WriteLine("Converted {0} ({1}) to {2}.", dateToSave.ToString(), dateToSave.Kind.ToString(), dateString); outFile.WriteLine(dateString); Console.WriteLine("Wrote {0} to {1}.", dateString, fileName); outFile.Close(); // Restore DateTime value. DateTime restoredDate; using StreamReader inFile = new StreamReader(fileName); dateString = inFile.ReadLine(); if (dateString is not null) { restoredDate = DateTime.Parse(dateString, null, DateTimeStyles.RoundtripKind); Console.WriteLine("Read {0} ({2}) from {1}.", restoredDate.ToString(), fileName, restoredDate.Kind.ToString()); } // The example displays the following output: // Converted 6/12/2008 6:45:15 PM (Local) to 2008-06-12T18:45:15.0000000-05:00. // Wrote 2008-06-12T18:45:15.0000000-05:00 to .\DateFile.txt. // Read 6/12/2008 6:45:15 PM (Local) from .\DateFile.txt. □ Round-trip a DateTimeOffset value const string fileName = @".\DateOff.txt"; StreamWriter outFile = new StreamWriter(fileName); // Save DateTime value. DateTimeOffset dateToSave = new DateTimeOffset(2008, 6, 12, 18, 45, 15, new TimeSpan(7, 0, 0)); string? dateString = dateToSave.ToString("o"); Console.WriteLine("Converted {0} to {1}.", dateToSave.ToString(), dateString); outFile.WriteLine(dateString); Console.WriteLine("Wrote {0} to {1}.", dateString, fileName); outFile.Close(); // Restore DateTime value. DateTimeOffset restoredDateOff; using StreamReader inFile = new StreamReader(fileName); dateString = inFile.ReadLine(); if (dateString is not null) { restoredDateOff = DateTimeOffset.Parse(dateString, null, DateTimeStyles.RoundtripKind); Console.WriteLine("Read {0} from {1}.", restoredDateOff.ToString(), fileName); } // The example displays the following output: // Converted 6/12/2008 6:45:15 PM +07:00 to 2008-06-12T18:45:15.0000000+07:00. // Wrote 2008-06-12T18:45:15.0000000+07:00 to .\DateOff.txt. // Read 6/12/2008 6:45:15 PM +07:00 from .\DateOff.txt.