C# UTC to Users Local Time

I have a site where users can make posts. The users can be from all over the globe so when they post, I am storing the posted date as DateTime.UtcNow. I am using the JQuery time ago plug in to show the posted dat similar to stack overflow (1 min ago etc…) But I am not sure how to convert to date I have stored in the system to the users local time? Here is what I am using:

public static MvcHtmlString ConvertToLocalTime(this HtmlHelper htmlHelper, DateTime date)
    {
        DateTime convertedDate = DateTime.SpecifyKind(DateTime.Parse(date.ToString()),DateTimeKind.Utc);
        return MvcHtmlString.Create(convertedDate.ToLocalTime().ToString());
    }

This sees to convert the time to the servers local time but I need it for the users local time. What am I doing wrong? I am using .NET MVC 2 and .NET 4.0

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

In general, you aren’t going to know the user’s exact time zone on the server side. Instead of trying to convert to the user’s local time on the server side, send the time to the client in UTC and have the client convert the time. The TimeAgo plugin does this automatically as long as you give it the time in full ISO8601 format:

<abbr class="timeago" title="2008-07-17T09:24:17Z">July 17, 2008</abbr>

The Z at the end of the timestamp is important; that means UTC.

Method 2

Do you have the culture for the current user? If so you could convert to their timezone using code from C# – Convert UTC/GMT time to local time


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x