将时区信息转换为datetime
本文关键字:datetime 转换 信息 时区 | 更新日期: 2023-09-27 18:13:57
如何将以下包含时区指定的日期时间字符串转换为日期时间类型?
这里是字符串"2011-11-27 23:59:59 EST"
这是我在msdn上发现的:
class Program
{
static void Main(string[] args)
{
// I realize here that the types don't match but just trying to
// illustrate what i'm trying to do
DateTime myDate = ReturnTimeOnServer("2011-11-27 23:59:59 EST");
}
public static DateTimeOffset ReturnTimeOnServer(string clientString)
{
string format = @"yyyy-mm-dd h:m:s zzz";
TimeSpan serverOffset = TimeZoneInfo.Local.GetUtcOffset(DateTimeOffset.Now);
try
{
DateTimeOffset clientTime = DateTimeOffset.ParseExact(clientString, format, CultureInfo.InvariantCulture);
DateTimeOffset serverTime = clientTime.ToOffset(serverOffset);
return serverTime;
}
catch (FormatException)
{
return DateTimeOffset.MinValue;
}
}
}
var myDate = DateTime.ParseExact("2011-11-27 23:59:59 EST",
"yyyy-MM-dd HH:mm:ss EST", CultureInfo.InvariantCulture);