Wednesday, 10 August 2016

Time Zone based UTC and Local Date Time Conversion (C#,MVC,Asp.Net,.Net)

Get offset from browser(client side front end):
 Reason:
              Client side because we use .Net system DateTime Offset means it will take file hosted server DateTime so take it client side and store it in cookies.
Put it in Layout page and Login page
Java Script:
<script>
        var d = new Date();//for getting time zone
        var n = d.getTimezoneOffset();//it will returns difference in minutes
        var TimezoneOffset = "TimezoneOffset=" + n;
        document.cookie = TimezoneOffset;
</script>


Server side common function C#:

// LocalToUtc for store date time in UTC

 public static DateTime LocalToUtc(DateTime LocalDT, double offset)
        {

            //if offset>0 then subtract offset else add offset
            //offset=UTC-Local Date Time
            if (offset < 0)//local date time > UTC
            {
                return LocalDT.AddMinutes(offset);//utc=local time - offset
                //example if LocalDT=6.00 and offset=-330(5.30) then UTC=0.30
            }
            else if (offset > 0)//local date time < UTC
            {
                return LocalDT.AddMinutes(offset * (-1));//
            }
            else { return LocalDT; }

        }

// UtcToLocal for Display date time in Local

public static DateTime UtcToLocal(DateTime UTCDT, double offset)
        {
            //return DT.AddMinutes(offset);
            //offset=UTC-Local Date Time
            if (offset < 0)//local date time > UTC
            {
                //DateTime x = UTCDT.AddMinutes(offset * -1);
                return UTCDT.AddMinutes(offset * (-1));//local time=utc + offset
                //example if LocalDT=6.00 and offset=-330(5.30) then UTC=0.30
            }
            else if (offset > 0)//local date time < UTC
            {
                //DateTime x = UTCDT.AddMinutes(offset);
                return UTCDT.AddMinutes(offset);
            }
            else { return UTCDT; }
        }
Controller or server side  C#:

public class TimeZoneCoversinController : Controller

    {
         //from cookies get TimezoneOffset
          double TimezoneOffset = double.Parse(Request.Cookies["TimezoneOffset"].Value.ToString());
           //user date time
              DateTime dt=DateTime.Now;   //Local time
              DateTime Utcdt=LocalToUtc(DateTime.Now,TimezoneOffset );//To UTC
              DateTime Localdt=UtcToLocal(Utcdt,TimezoneOffset );//To Local
           
     }