c# - How to Convert a Time to local Time in Different TimeZone -
currently working on chat project many users can communicate through each other sitting across globe. ie: different timezone. eg. 1st in india 2nd in america 3rd in russia 4th in australia
i saving message sent time database datetime.now.touniversaltime() issue getting if user sent message gets correct time 1 min ago rest time 4 hours ago . every person sitting across different countries should 1 min ago using javascript timezone like
var offset = new date().gettimezoneoffset(); $("#timezoneoffset").val(offset); //setting timezone in hidden field , save cookie. to convert utc time database 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 sent india above time, seconds ago partner sitting in north america gets 4 hours ago.
what doing wrong? code 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 see code first line in timeago() method: datetime dt object pass method local time clients, use server local time datetime.now calculate timespan.
pass utc timestamps db method directly , replace datetime.now datetime.utcnow.
Comments
Post a Comment