我们的数据库服务器在国外。所以我使用TimeZoneInfo存储了创建的日期,如下所示,
DateTime dateTime = DateTime.Now;
var timeZone = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dateTime, TimeZoneInfo.Local.Id, "India Standard Time");
在页面中,我显示Timespan 已使用。我为此创建了单独的类..
我的代码
public static string GetFriendlyDate(DateTime dateTime)
{
TimeSpan ts = DateTime.Now.Subtract(dateTime);
string friendlyDate = dateTime.ToShortDateString();
int totalDays = (int)System.Math.Round(ts.TotalDays);
int totalHours = (int)System.Math.Round(ts.TotalHours);
int totalMinutes = (int)System.Math.Round(ts.TotalMinutes);
int totalSeconds = (int)System.Math.Round(ts.TotalSeconds);
int totalMilliSeconds = (int)System.Math.Round(ts.TotalMilliseconds);
int totalMonths = totalDays / 31; //approx.. change this
int totalYears = totalDays / 365; //approx.. change this
if (totalYears > 0) //give in terms of years
{
if (totalYears == 1)
friendlyDate = "last year";
else
friendlyDate = totalYears + " years ago";
}
else if (totalMonths > 1) //give in terms of months
{
if (totalMonths == 1)
friendlyDate = "last month";
else
friendlyDate = totalMonths + " months ago";
}
else if (totalDays > 1) //give in terms of days (at least 2 days)
{
friendlyDate = totalDays + " days ago";
}
else if (totalHours > 0) //give in terms of hours
{
if (totalHours == 1)
friendlyDate = "1 hour ago";
else
friendlyDate = totalHours + " hours ago";
}
else if (totalMinutes > 0) // give in terms of minutes
{
if (totalMinutes == 1)
friendlyDate = "1 minute ago";
else
friendlyDate = totalMinutes + " minutes ago";
}
else if (totalSeconds > 0) //give in terms of seconds
{
if (totalSeconds == 1)
friendlyDate = "1 second ago";
else
friendlyDate = totalSeconds + " seconds ago";
}
else //just now
{
friendlyDate = "a moment ago";
}
return friendlyDate;
}
当我在本地运行时,它正确显示“--seconds ago”......就像那样..但在服务器中它总是显示在片刻之前,几个小时后它需要“---hours ago”这样......
谁能帮我解决这个问题?