C# 显示更改为本地时间后的timespan值
我们的数据库服务器在国外。。因此,我使用TimeZoneInfo存储创建的日期,如下所示:C# 显示更改为本地时间后的timespan值,c#,datetime,timespan,C#,Datetime,Timespan,我们的数据库服务器在国外。。因此,我使用TimeZoneInfo存储创建的日期,如下所示: DateTime dateTime = DateTime.Now; var timeZone = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dateTime, TimeZoneInfo.Local.Id, "India Standard Time"); 在第页中,我显示被时间跨度使用的时间。我为此创建了单独的类 我的代码 public sta
DateTime dateTime = DateTime.Now;
var timeZone = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dateTime, TimeZoneInfo.Local.Id, "India Standard Time");
在第页中,我显示被时间跨度使用的时间。我为此创建了单独的类
我的代码
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;
}
当我运行local时,它会正确地显示“--秒前”。。。像那样。。但在服务器中,它总是在片刻前显示,在几个小时后,它会以“--hours ago”这样的方式显示
谁能帮我解决这个问题 如果我想正确回答我的问题,我必须将时间转换为UTC 所以我改变了
var utcTime = DateTime.UtcNow.AddHours(5).AddMinutes(30);
TimeSpan ts = utcTime.Subtract(dateTime);
现在问题已经解决了…您正在存储印度标准时间的项目,然后将其与当地时间进行比较 您在回答中给出的解决方案是将时间调整回印度标准时间,该时间固定为UTC的
+5:30
偏移量。这仅仅是因为IST没有任何夏令时规则。如果您使用不同的时区,例如美国东部时间,它将无法可靠地工作
正确的解决方案是将原始值存储为UTC。不要使用DateTime.Now
并转换为IST,只需使用DateTime.UtcNow
并直接存储值即可。在GetFriendlyDate
方法中进行比较时,还应使用DateTime.UtcNow
作为比较的基础
如果已经在印度标准时间将数据保存在数据库中,则在进行此更改时需要更新这些值。例如,如果这是SQL Server,则可以运行以下脚本将值从IST更新为UTC:
UPDATE mytable SET thedatetime = DATEADD(minute, -330, thedatetime)
一般来说,本地日期/时间值(如从DateTime.Now
检索的值)与web应用程序没有任何关系。阅读