我在SQL服务器中有一个用于不同时区的表,我在IT中有一个美国(-5:00)的条目....我在字符串中得到它的值为-5:00,但是当我尝试使用Convert.ToDateTime或DateTime.parse转换它,它抛出异常,如何将" -5:00"(字符串)转换为DateTime ???
string meetingtotimezone = db.Users.FirstOrDefault(u => u.UserId == model.MeetingToId).TimeZone.TimeZone1; // here i have "-5:00" value as string
DateTime meetingtotimezonedate = DateTime.Parse(meetingtotimezone); // throwing exception
DateTime meetingtotimezonedate = Convert.ToDateTime(meetingtotimezone); // throwing exception
答案 0 :(得分:1)
您可以使用TimeSpan方法将时区值转换为Parse。然后,您可以使用该值计算,就好像它是一个数字:
string input = "-5:00";
TimeSpan difference = TimeSpan.Parse(input);
// this meeting would be at 14:00
DateTime meetingTime = new DateTime(2018, 1, 20, 14, 0,0,0);
// time of the meeting in the other timezone
DateTime meetingtotimezonedate = meetingTime + difference;
Console.WriteLine(meetingtotimezonedate.ToShortTimeString());
输出:
09:00