How to change time zone for an asp.net application

前端 未结 6 942
一个人的身影
一个人的身影 2020-12-31 03:43

I need to set default timezone for my ASP.NET to Asia/Dhaka or GMT+6 timezone. But i cannot find a way to change it globally. There is a lot of reference on Stackoverflow an

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-31 03:56

    Having a similar issue (with Time zones) I ended up changing some database types from DateTime to DateTimeOffset (MSSql).

    DateTimeOffset Struct

    Wrote an extension

    public static class Extensions
    {
        public static DateTimeOffset ToCentralTime(this DateTimeOffset value)
        {
            return TimeZoneInfo.ConvertTime(value, TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"));
        }
    }
    

    Example of use:

    public class ClockPunch
    {
        private DateTimeOffset dtoTimeIn;
        private DateTimeOffset? dtoTimeOut;
        public ClockPunch() { }
        public DateTimeOffset TimeIn
        {
            get { return dtoTimeIn.ToCentralTime(); }
            set { dtoTimeIn = value; }
        }
        public DateTimeOffset? TimeOut
        {
            get
            {
                DateTimeOffset? retVal = null;
                if (dtoTimeOut != null)
                {
                    retVal = ((DateTimeOffset)dtoTimeOut).ToCentralTime();
                }
                return retVal;
            }
            set { dtoTimeOut = value; }
        }
    }
    

提交回复
热议问题