C# DateTime 將日期字符串格式化為帶時區的日期格式


需求:參數,一個日期字符串,不帶時區的那種,一個TimeZoneID。將其轉換為UTC時間。

            //可以獲取所有的TimeZoneID
            IList<TimeZoneInfo> lst = TimeZoneInfo.GetSystemTimeZones();

            //當日期格式為 2021-05-31T09:00:00Z 時會轉換異常。
            string str = "5/18/2021 7:00 AM";

            //目前尚未研究清楚這個是什么時間格式
            var aa = Convert.ToDateTime("2021-05-31T09:00:00Z").ToString("M/d/yyyy hh:mm:ss tt", System.Globalization.DateTimeFormatInfo.InvariantInfo);
            Console.WriteLine(aa); //5/31/2021 05:00:00 PM

            //(GMT-04:00) Eastern Time (US and Canada)
            var esternTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");

            if (DateTime.TryParse(str, out DateTime dt))
            {
                //var formattedDate = new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, DateTimeKind.Unspecified);

                ///獲取對應的utc時間
                var utcStartTime = TimeZoneInfo.ConvertTimeToUtc(dt, esternTimeZone);
                var result = utcStartTime.ToString("yyyy-MM-ddTHH:mm:ssZ");
                Console.WriteLine(result); //2021-05-18T11:00:00Z
            }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM