私はこれを理解しようと午後中ずっと頭を悩ませてきました。基本的に、問題自体は単純に見えます。別のタイムゾーン(ローカルではない)の日付と時刻を表す日付/時刻が与えられます。この値をUTC値に変換して、データベースに保存したいと思います。ただし、オンラインで見つけたすべての方法は、UTCで開始するか、ローカルタイムゾーンで開始することを示しているようです。これらから他のタイムゾーンに変換することはできますが、それ以外のものから始めることはできません。結果として、私がやりたいことをするために、ある種の複雑なオフセット計算をしなければならないように思われます。問題の例を次に示します。
var dateString = "8/20/2014 6:00:00 AM";
DateTime date1 = DateTime.Parse(dateString,
System.Globalization.CultureInfo.InvariantCulture);
var currentTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
// Now the server is set to Central Standard Time, so any automated offset calculation that it runs will come from that point of view:
var utcDate = date1.ToUniversalTime; // This is wrong
// Similarly, if I try to reverse-calculate it, it doesn't work either
var convertedDate = TimeZoneInfo.ConvertTime(date1, currentTimeZone);
utcDate = convertedDate.ToUniversalTime; // This is also wrong
In essence, I want to somehow tell the system that the datetime object I'm currently working with is from that time zone other than local, so that I know the conversion will be correct. I know that I'll eventually need to figure Daylight Savings Time in there, but that is a problem for another day.
Would this method be of any use to you ?
The TimeZoneInfo.ConvertTime method converts a time from one time zone to another.
Alternatively, you could use the ConvertTimeToUtc
method to simply convert any date (specifying the source time zone) to UTC.
var dateString = "8/20/2014 6:00:00 AM";
DateTime date1 = DateTime.Parse(dateString,
System.Globalization.CultureInfo.InvariantCulture);
var currentTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
var utcDate = TimeZoneInfo.ConvertTimeToUtc(date1, currentTimeZone);
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加