如何在c#中将字符串偏移量转换为时间跨度 [英] How to convert string offset to timespan in c#
问题描述
我正在尝试将转换时间转换为用户的时区,但我没有 Windows 时区字符串,例如太平洋标准时间".我所拥有的只是一个字符串偏移量,例如-07:00".看起来我需要创建一个时间跨度.是手动解析这个字符串的唯一方法吗?似乎应该有一种使用字符串偏移量转换时间的方法,但也许我遗漏了一些东西.
I'm trying to convert the convert time to the user's time zone, but I don't have the windows time zone string such as "Pacific Standard Time". All I have is a string offset such as "-07:00". Looks like I need to create a timespan. Is the only way to parse this string manually?. Seems like there should be a way to convert a time using a string offset, but maybe I am missing something.
我有这个,但它需要时区.我正在尝试修改它以使用偏移量,但您可以看到为转换创建的时间跨度,我需要将偏移量设置为时间跨度.
I have this but it requires the timezone. I'm trying to modify it to use the offset instead, but you can see the timespan that is created for the conversion and I need to get my offset to the timespan.
static void Main(string[] args)
{
var currentTimeInPacificTime = ConvertUtcTimeToTimeZone(DateTime.UtcNow, "Pacific Standard Time");
//TimeSpan ts = new TimeSpan("-07:00");
Console.ReadKey();
}
static DateTimeOffset ConvertUtcTimeToTimeZone(DateTime dateTime, string toTimeZoneDesc)
{
if (dateTime.Kind != DateTimeKind.Utc) throw new Exception("dateTime needs to have Kind property set to Utc");
TimeSpan toUtcOffset = TimeZoneInfo.FindSystemTimeZoneById(toTimeZoneDesc).GetUtcOffset(dateTime);
var convertedTime = DateTime.SpecifyKind(dateTime.Add(toUtcOffset), DateTimeKind.Unspecified);
return new DateTimeOffset(convertedTime, toUtcOffset);
}
推荐答案
您只需使用 TimeSpan.Parse
方法:
You can just use the TimeSpan.Parse
method:
TimeSpan ts = TimeSpan.Parse("-07:00");
Console.WriteLine(ts); // -07:00:00
小心去掉前导的+"因为 TimeSpan.Parse 会在这里失败.+01:00"不正确,但01:00"有效.
Be careful to strip a leading "+" as TimeSpan.Parse will fail here. "+01:00" is incorrect, but "01:00" works.
或者,如果您想要更安全一点,请尝试TimeSpan.TryParse
方法:
Or if you want be a little more safe, try the TimeSpan.TryParse
method:
TimeSpan ts;
if (TimeSpan.TryParse("-07:00", out ts))
Console.WriteLine(ts); // -07:00:00
当然,如果您只想将 UTC 日期/时间转换为本地日期/时间,您可以这样做:
But of course if all you want to do is convert a UTC date/time to a local date/time, you can just do this:
DateTime localDateTime = utcDateTime.ToLocalTime();
或将其转换为任何时区:
Or to convert it to any timezone:
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById(toTimeZoneDesc);
DateTime localDateTime = TimeZoneInfo.ConvertTime(utcDateTime, tzi);
这篇关于如何在c#中将字符串偏移量转换为时间跨度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!