以下のコードを使用して、NodaTime の LocalDateTime パターンを使用して、ゾーン化された日時から UTC 時刻を取得しようとしています。
public string getUtcTimeFromZonedTime(string dateTimeString, string timeZoneID,
string dateTimePattern, bool isDateTime)
{
if (string.IsNullOrEmpty(dateTimePattern))
{
if (isDateTime)
{
dateTimePattern = "M/dd/yyyy HH:mm:ss tt";
}
else
{
dateTimePattern = "M/dd/yyyy";
}
}
var pattern = LocalDateTimePattern.CreateWithInvariantCulture(dateTimePattern);
var parseResult = pattern.Parse(dateTimeString);
if (!parseResult.Success)
{
// throw an exception or whatever you want to do
}
var localDateTime = parseResult.Value;
var timeZone = DateTimeZoneProviders.Tzdb[timeZoneID];
// TODO: Consider how you want to handle ambiguous or "skipped" local date/time
// values. For example, you might want InZoneStrictly, or provide your own custom
// handler to InZone.
var zonedDateTime = localDateTime.InZoneLeniently(timeZone);
return zonedDateTime.ToDateTimeUtc().ToString();
}
以下のシナリオでの解析中に例外が発生します。1) パターンが「MM/dd/yyyy HH:mm:ss tt」のようで、DateTime 文字列が「5/28/2013 1:02:ss PM」のような場合2) パターンが「MM-dd-yyyy HH:mm:ss tt」のようなもので、DateTime 文字列が「5/28/2013 1:02:ss PM」のようなものである場合
最初のケースでは、パターンを「M/dd/yyyy HH:mm:ss tt」に変更すると機能しますが、先頭のゼロが失われてしまいます。パターンを「MM/dd/yyyy HH:mm:ss tt」に変更すると、2 番目のケースが機能します。
UTC 値を取得する別の方法はありますか、それともここで何か間違ったことをしていますか?