Mike Borozdin's Blog

A blog about programming, web and IT in general

Follow Me

Search

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© 2014 Mike Borozdin

Getting BlogEngine.NET To Work With The Local Time Zones

I noticed that the times of posts and comments were displayed in my local time zone. It must be very confusing for the users, especially if those times were the times of the comments they posted.


The first idea that came to my mind was just to use the GMT time zone. I set up the time zone offset in the blog settings, changed the templates, basically, I just put “GMT” after the time.


Anyway that still wasn’t good enough. I wanted the times of the posts and comments to be displayed in the local time zones of my readers.

Since it’s not possible to get the time zone offset of the user in ASP.NET without interacting with JavaScript, I decided to solve the problem in pure JavaScript. I just wrote a function that converted the string that represents the date and the time in GMT to the date and time of the local time zone of the user.

function ConvertToLocalDate(gmtDate)
{
    gmtDate = gmtDate.substr(gmtDate.indexOf(",", 0) + 1);
    
    var days = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
        "Saturday");
    var months = new Array("January", "February", "March", "April", "May", "June", "July", "August",
        "September", "November", "December");    
    
    var localDate = new Date();
    localDate.setTime(Date.parse(gmtDate) - localDate.getTimezoneOffset() * 60 * 1000);
    
    var sLocalDate = days[localDate.getDay()] + ", ";
    sLocalDate += months[localDate.getMonth()] + " ";
    sLocalDate += localDate.getDate() + ", ";
    sLocalDate += localDate.getFullYear() + " ";
    
    var hours = localDate.getHours();
    var amPm = "AM";
    if (hours >= 12)
    {
        amPm = "PM";
        if (hours >= 13)
        {
            hours -= 12;
        }
    }
    
    if (hours < 10)
    {
        hours = "0" + hours.toString();
    }
    
    var minutes = localDate.getMinutes();
    
    if (minutes < 10)
    {
        minutes = "0" + minutes.toString();
    }
    
    sLocalDate += hours + ":" + minutes + " " + amPm;
    
    return sLocalDate;
}


I placed this function in blog.js. Then I changed PostView.aspx and CommentView.aspx. I replaced:


<%=Post.DateCreated.ToLongDateString() + " " + Post.DateCreated.ToShortTimeString() %>

with


<script type="text/javascript">     document.write(ConvertToLocalDate('<%=Post.DateCreated.ToLongDateString() + " " + Post.DateCreated.ToShortTimeString() %>')); </script>

Kick it! Shout it

Posted on Thursday, June 19, 2008
Comments (5)
blog comments powered by Disqus