简体   繁体   English

如何使用不考虑时区的Convert.ChangeType将字符串转换为日期时间

[英]How to convert string to datetime using Convert.ChangeType not considering timezone

This code adds time zone to DateTime, in the real scenario this code is inside a generic function to convert strings to various types. 此代码将时区添加到DateTime,在实际场景中,此代码位于通用函数内,以将字符串转换为各种类型。 So I need a generic code to work to all types: 所以我需要一个通用代码来适用于所有类型:

DateTime d = DateTime.MinValue;
string s = "2006-10-31T11:17:50Z";
d = (DateTime)Convert.ChangeType(s, typeof(DateTime),CultureInfo.InvariantCulture);

On my PC with +1 timezone d is: {31/10/2006 12:17:50} 在我的电脑上有+1时区d是:{31/10/2006 12:17:50}

Is there a way to ignore the time zone? 有没有办法忽略时区?

I can't use DateTime.Parse nor DateTime.ParseExact . 我不能使用DateTime.ParseDateTime.ParseExact

I guess you receive the type you want to convert into as a parameter and that's why you can't use DateTime.Parse... But can you at least test for the type ? 我猜你收到你想要转换成参数的类型,这就是为什么你不能使用DateTime.Parse ...但是你至少可以测试一下这个类型吗? something like that is not the prettiest but should work: 像这样的东西不是最漂亮但应该工作:

var s = "2006-10-31T11:17:50Z";
var t = typeof(DateTime);
var d = Convert.ChangeType(s, t, CultureInfo.InvariantCulture);

if (t == typeof(DateTime))
   d = TimeZoneInfo.ConvertTimeToUtc((DateTime)d);

Console.WriteLine(d.ToString());

Output 产量

10/31/2006 11:17:50 AM

Using generics (you can adapt to fit your needs): 使用泛型(您可以根据自己的需要进行调整):

public TDest ConvertValue<TSrc, TDest>(TSrc src, Func<TDest, TDest> adapter = null)
{
    var converted = Convert.ChangeType(src, typeof(TDest), CultureInfo.InvariantCulture);
    if (adapter == null)
    {
        adapter = GetDefaultAdapter<TDest>();
    }
    return adapter(converted);
}

private static readonly Hashtable DefaultAdapters = InitializeAdapters();
private static Hashtable InitializeAdapters()
{
    var hashtable = new Hashtable
    {
        {typeof (DateTime).Name, (Func<DateTime, DateTime>)(t => DateTime.SpecifyKind(t, t.ToUniversalTime())},
    };

    return hashtable;
}

public static Func<T, T> GetDefaultAdapter<T>()
{
    Func<T, T> ret = f => f;
    if (DefaultAdapters.ContainsKey(typeof(T).Name))
    {
        ret = (Func<T, T>)DefaultAdapters[typeof(T).Name];
    }

    return ret;
}

如果您知道时区与目标时区之间的时差,则可以使用DateTimeOffset来包含所述差异。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM