Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Team,
Could you please assist with the below requirement I am facing the issue while converting from DateTime to DateTimeOffset while using Mapper.Map
Getting error:
Unable to cast object of type 'System.DateTimeOffset' to type 'System.IConvertible

I have tried with the below code
class Program
    {
        static void Main(string[] args)
        {
            A a = new A();
            a.ADate = DateTime.Now.AddDays(2);
            B b = new B();
            b.BDate = DateTime.Now.AddDays(6);
            a.ADate = Convert.ToDateTime(b.BDate);
            Mapper.Map(a, b);
            Console.WriteLine("Hi" + b.BDate);
            Console.Read();
        }
    }
    class A
    {
        public DateTime ADate { get; set; }
    }
    class B
    {
        public DateTimeOffset BDate { get; set; }
    }


What I have tried:

class Program
    {
        static void Main(string[] args)
        {
            A a = new A();
            a.ADate = DateTime.Now.AddDays(2);
            B b = new B();
            b.BDate = DateTime.Now.AddDays(6);
            a.ADate = Convert.ToDateTime(b.BDate);
            Mapper.Map(a, b);
            Console.WriteLine("Hi" + b.BDate);
            Console.Read();
        }
    }
    class A
    {
        public DateTime ADate { get; set; }
    }
    class B
    {
        public DateTimeOffset BDate { get; set; }
    }
Posted
Updated 31-Jan-23 10:27am

1 solution

I do not use the Mapper[^] lib, but, for a better understanding of how they work, I will give you examples of doing it manually.

Below are examples of working with the DateTime[^] and DateTimeOffset[^], using TimeZoneInfo[^]:
C#
using System.Diagnostics;

const string dateString = "2012-11-20T00:00:00Z";

// this timezone has an offset of +01:00:00 on this date
TimeZoneInfo timezone = TimeZoneInfo
    .FindSystemTimeZoneById("W. Europe Standard Time");

DateTimeOffset utc = DateTimeOffset.Parse(dateString);
DateTimeOffset result = TimeZoneInfo.ConvertTime(utc, timezone);

// the correct utc offset, in this case +01:00:00
Debug.Assert(result.Offset == new TimeSpan(1, 0, 0));

//equals the original date
Debug.Assert(result.UtcDateTime == new DateTime(2012, 11, 20, 0, 0, 0));
Debug.Assert(result.DateTime == new DateTime(2012, 11, 20, 1, 0, 0));

Lastly, for Mapper, it appears that you need to use a Custom Type Converter[^]. The above example should help you in doing this.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900