我创建了一些我需要测试的DateTime扩展。为了测试它们,我需要能够模拟DateTime实例代表创建实例的本地服务器之外的各种时区。.NET中非本地时区的DateTime实例
我曾尝试以下...
//
// Create the new date to test. It will be in the timezone of the server it was created on (EST).
DateTime localDate = new DateTime(2017, 11, 14, 12, 0, 0);
//
// Get the TimeZone for another locale
TimeZoneInfo newTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Egypt Standard Time");
//
// Convert the localDate into a DateTime instance as if created on a server located in
// "Egypt Standard Time". - NOT WORKING
DateTime test = TimeZoneInfo.ConvertTime(localDate, origTimeZone);
//
// run the test
Boolean result = test.ExtensionMethod()
但是,这不仅导致“测试”在当地EST TZ是和另外一个DateTime。时间已经改变,以反映在埃及的时间,但实例,当评估...例如,转换为“通用时间”,仍然转换,就像它是一个EST时区。
鉴于前面的例子,我的变量“test”将包含DateTime“2017-11-14 19:00:00”。当我将它转换为UTC时,我'HOPING'的结果'2017-11-14 17:00:00'。相反,我得到'2017-11-15 00:00:00。
有没有办法从除本地服务器以外的其他时区实例化DateTime?
存在过载到从日期时间中特定的区域转换为UTC。无论如何,在处理这个问题时,使用UTC作为基本的“时区”是一个好主意:您只需要花费时间进行输入和输出,核心应该可以工作。 –
虽然我很欣赏评论,承认并完全同意你所描述的做法......但不幸的不是我的情况。我真正需要知道的是,如果我所要求的是可以做到的。它是否应该做,是间接的,我已经开始与项目团队进行讨论......再次感谢您的反馈。 –
您可能在这里使用了错误的变量: TimeZoneInfo.ConvertTime(localDate,'origTimeZone'); –