, , ,

How to Get/Set date time according to Different Time zones in C#

downloadDownload code example

In an Asp.net application I have developed a Forum in which I have requirement to show date and time according to the time zone of PC on which it is running, I had searched for too many examples on but all are using too complex java scripts and other methods to convert time into local time zone.

Finally I decided to make my own solution for this problem
My solution is using “TimeZoneInfo” to convert the data to local time zone, this class allow me to convert time according to any time zone, but again I got another problem which is how to take time zone of browser. Again I search on net and finally come out with a code.

<script language="javascript" type="text/javascript">
    function genarateDateValue()
    {             
        var d = new Date()      
        var str=d.toString();
        var i = str.indexOf("+");      
        var j = str.length- i;
      
        str=str.substring(i, i+5);      
        setCookie("narender",str,365);
        return true;
       }

    function setCookie(c_name,value,expiredays)
    {      
        var exdate=new Date();
        exdate.setDate(exdate.getDate()+expiredays);
        document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
    }  
</script>

In Sql Server still there is no method to covert from one time zone to another but My Sql Support converting date time according to provided time zone.
Following is the simple code runs on My Sql Prompt:-
CONVERT_TZ(dt,from_tz,to_tz)
CONVERT_TZ() converts a datetime value dt from the time zone given by from_tz to the time zone given by to_tz and returns the resulting value. This function returns NULL if the arguments are invalid.
If the value falls out of the supported range of the TIMESTAMP type when converted from from_tz to UTC, no conversion occurs.
mysql> SELECT CONVERT_TZ('2004-01-01 12:00:00','GMT','MET');
        -> '2004-01-01 13:00:00'
mysql> SELECT CONVERT_TZ('2004-01-01 12:00:00','+00:00','+10:00');
        -> '2004-01-01 22:00:00'

Above is the method which we can use in My Sql which will return all the values from Database itself but if we are using Sql server we need to write our own code to convert time zone in C# code.
You can also download this code from link provided on top on this post.
public string DateFormat(string str)
    {
        ReadOnlyCollection<TimeZoneInfo> timeZones = TimeZoneInfo.GetSystemTimeZones();
        foreach (TimeZoneInfo timeZone in timeZones)
        {
            TimeSpan offsetFromUtc = timeZone.BaseUtcOffset;
            string offsetString;
            string strHours = string.Empty;
            string strMinutes = string.Empty;
            strHours = offsetFromUtc.Hours.ToString();
            strMinutes = offsetFromUtc.Minutes.ToString();
            if (strMinutes.Length == 1)
            {
                strMinutes = "0" + strMinutes;
            }
            if (strHours.Length == 1)
            {
                strHours = "0" + strHours;
            }

            if (Convert.ToInt32(offsetFromUtc.Hours) >= 0)
            {
                strHours = "+" + strHours;
            }
            offsetString = strHours + strMinutes;
            if (Request.Cookies["narender"] != null)
            {
                if (Request.Cookies["narender"].Value.ToString() == offsetString)
                {
                    if (str != "")
                    {
                        DateTime thisTime = Convert.ToDateTime(str);
                        TimeZoneInfo tst1 = TimeZoneInfo.FindSystemTimeZoneById(timeZone.Id);
                        DateTime tstTime1 = TimeZoneInfo.ConvertTime(thisTime, TimeZoneInfo.Local, tst1);
                        str = Convert.ToDateTime(tstTime1).ToString("dddd,MMMM dd,yyyy hh:mm:ss tt");
                    }
                    return str;
                }
            }
        }
        return str;
    }
Share:

2 comments:

We are Liverpool said...

Well,can you please gibe me the code to convert time zone on just a click?

IT Solutions said...

This article was really nicely created, and it also consists of numerous helpful details. I valued your expert manner of writing this article. You’ve made it is easy for me to understand.

Great Solution!