[英]Date value gets saved differently when client and server time zones are different
我的AngularJS客户端将以纪元毫秒为单位的日期值传递给使用C#.NET的服务器。 我的客户端和服务器位于不同的时区。 我从客户端传递日期值,如下所示,它返回纪元毫秒:
var date = $scope.date.getTime()
如果我从客户选择的日期为' Tue Jan 16 2018 00:00:00 GMT + 0530(India Standard Time) ',则纪元值对应于1516041000000
但是,当我将此纪元传递到我的服务器端时,GMT / UTC时间即2018年1月15日星期一6:30:00 PM将保存到我的数据库中。
我试图通过我的API标头将GMT偏移量传递到服务器,并将偏移量值添加到UTC时间。 但这会导致夏时制的问题,因为对于各种日期值,偏移量是不同的。
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var savedDate = epoch.AddMilliseconds(long.Parse(passedDateEpoch)).AddMinutes(ClientGmtOffset);
有什么方法可以使用纪元时间值本身将输入的确切日期保存在服务器数据库中。 我不希望将任何时间部分或不正确的日期保存到数据库中。
使用可以指定webapiconfig文件中未指定的时间。有关更多信息,例如[是否将C#datetime本地时间保留在json和Web api之间?
您可以指定以下内容,以避免从服务器端进行时间转换
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
//subhash
log4net.Config.XmlConfigurator.Configure();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { action = RouteParameter.Optional, id = RouteParameter.Optional }
);
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Unspecified;
config.Services.Replace(typeof(IExceptionHandler), new CustomExceptionHandler());
}
我希望这能帮到您
尝试这个:
double dateFromClient = double.Parse("1521707203364");
var savedDate = (new DateTime(1970, 1, 1)).AddMilliseconds(dateFromClient);
但是我认为最好将Unix Timestamp(例如1521707203364)保存在数据库中,然后在将其返回给客户端时,客户端再次解析它并获取正确的Date。
您可以在服务器端使用以下代码
public struct DateTimeWithZone
{
private readonly DateTime utcDateTime;
private readonly TimeZoneInfo timeZone;
public DateTimeWithZone(DateTime dateTime, TimeZoneInfo timeZone)
{
var dateTimeUnspec = DateTime.SpecifyKind(dateTime, DateTimeKind.Unspecified);
utcDateTime = TimeZoneInfo.ConvertTimeToUtc(dateTimeUnspec, timeZone);
this.timeZone = timeZone;
}
public DateTime UniversalTime { get { return utcDateTime; } }
public TimeZoneInfo TimeZone { get { return timeZone; } }
public DateTime LocalTime
{
get
{
return TimeZoneInfo.ConvertTime(utcDateTime, timeZone);
}
}
}
这样从前端返回日期
var date = new Date();
var isoDate = date.toISOString()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.