将本地时间转换为特定时区,而不考虑夏令时开启 [英] Convert Local time to a Specific timezone irrespective of Daylight is ON
问题描述
我想将本地时间转换为PST(不是PDT当前的日光)
我想有这种方法通用,所以我可以使用这个任何时区不只是太平洋。 p>
I would like to convert local time to PST (Not PDT as its Daylight on currently) And I would like to have this method generic so that I can use this for any timezone not only for Pacific.
public static DateTime ConvertDateToTimezone(DateTime givenDateTime, string timezoneId, bool considerDaylight)
{
if (!considerDaylight)
{
//ToDo need to implement
// Convert time to "timezoneId" irrespective of Daylight is on or not.
// var timezone =
// TimeZoneInfo.GetSystemTimeZones()
// .FirstOrDefault(x => x.Id.Equals(timezoneId));
// TimeZoneInfo.ConvertTimeBySystemTimeZoneId(givenDateTime, timezoneId);
}
return TimeZoneInfo.ConvertTimeBySystemTimeZoneId(givenDateTime, timezoneId);
}
推荐答案
那么你可以这样做:
public static DateTimeOffset ConvertToTimeZone(DateTimeOffset dto, string timeZoneId, bool considerDaylight)
{
var timeZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
if (considerDaylight)
{
// this is the normal behavior
return TimeZoneInfo.ConvertTime(dto, timeZone);
}
else
{
// the base offset doesn't include DST adjustment
return dto.ToOffset(timeZone.BaseUtcOffset);
}
}
但是,像Jon在问题评论中提到的,不推荐。你应该存储UTC。您真的应该回去与您的客户讨论这个问题。
However, like Jon mentioned in the question comments, this isn't recommended. You should probably be storing UTC. You really should go back and discuss this with your customer.
此外,请注意,有时,DST调整用于非DST用途,例如当时区更改其基点偏移在一年中。这种情况经常发生在美国以外。
Also, recognize that sometimes the DST adjustment is used for non-DST purposes, such as when a time zone changes its base offset in the middle of a year. This happens fairly often outside of the USA.
这篇关于将本地时间转换为特定时区,而不考虑夏令时开启的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!