Currently i am working on a chat project from where many users can communicate through each other sitting across the globe. ie: Different TimeZone. eg. 1st in India 2nd in America 3rd in Russia 4th in Australia
I am saving my message sent time into database as DateTime.Now.ToUniversalTime() Issue i am getting is if any user sent message he gets correct time like 1 min ago but rest will get time like 4 hours ago . Every person sitting across different countries should get 1 Min ago I am using javascript to get timezone like
var offset = new Date().getTimezoneOffset();
$("#timezoneOffset").val(offset); //setting timezone in hidden field and save as cookie.
To Convert UTC time from database to show client time difference :
var timeOffSet = Request.Cookies["timeoffset"].Value;
DateTime dt = Convert.ToDateTime("2015-06-15 12:13:12");
if (timeOffSet != null)
{
var offset = int.Parse(timeOffSet.ToString());
dt = dt.AddMinutes(-1 * offset);
model.SentDate = FormatTime.TimeAgo(dt);
}
This message I sent from india with above time, I Get a seconds ago but my partner sitting in North America gets 4 hours ago.
What i am Doing Wrong? My Code to convert DateTime in ago format is:
public static string TimeAgo(DateTime dt)
{
TimeSpan span = DateTime.Now - dt;
if (span.Days > 365)
{
int years = (span.Days / 365);
if (span.Days % 365 != 0)
years += 1;
return String.Format("about {0} {1} ago",
years, years == 1 ? "year" : "years");
}
if (span.Days > 30)
{
int months = (span.Days / 30);
if (span.Days % 31 != 0)
months += 1;
return String.Format("about {0} {1} ago",
months, months == 1 ? "month" : "months");
}
if (span.Days > 0)
return String.Format("about {0} {1} ago",
span.Days, span.Days == 1 ? "day" : "days");
if (span.Hours > 0)
return String.Format("about {0} {1} ago",
span.Hours, span.Hours == 1 ? "hour" : "hours");
if (span.Minutes > 0)
return String.Format("about {0} {1} ago",
span.Minutes, span.Minutes == 1 ? "minute" : "minutes");
if (span.Seconds > 5)
return String.Format("about {0} seconds ago", span.Seconds);
if (span.Seconds <= 5)
return "just now";
return string.Empty;
}
The main problem I see with your code is the first line in your
TimeAgo()
method: TheDateTime dt
object you pass to this method is local time for your clients, but then you use the server local timeDateTime.Now
to calculate the timespan.Pass the UTC timestamps you get from your DB to this method directly and replace
DateTime.Now
withDateTime.UtcNow
.