【问题标题】:keep C# datetime local time between json and Web api?在 json 和 Web api 之间保持 C# datetime 本地时间?
【发布时间】:2015-08-18 14:04:22
【问题描述】:

当我在 json 对象中有数据时间时遇到问题,它会将其转换为 C# 中的 UTC 时区 dateTime 只是想问如何保持本地时间?我可以在 web.config 文件或 geter 或 setter 中设置时区属性吗?我必须可以反对有日期和时间? 这是类示例?

public class Patient
{
    public long RecordId { get; set; }
    public string Username { get; set; }
    public DateTime Date 
      {
          get; 
          set;
      }
    public bool Deleted { get; set; }
    public string ModifiedBy { get; set; }
    public DateTime ModifiedOn { get; set; }
    public string CreatedBy { get; set; }
    public DateTime CreatedOn { get; set; }
}

更新我尝试使用 getter 和 setter 来修复我有这个异常{Cannot evaluate expression because the current thread is in a stack overflow state.}

[System.Web.Http.Route("api/postpatientform")]
public HttpResponseMessage PostPatientForm(PatientViewModel form)
{
    using (var db = new AthenaContext())
    {
        try
        {
            var form2 = Mapper.Map<Patient>(form);
            db.Patient.Add(form2);
            db.SaveChanges();

            var newId = form2.RecordId;
            foreach (var activity in form.PatientActivities)
            {
                activity.PatientId = newId;

                db.NonPatientActivities.Add(Mapper.Map<PatientActivity>(activity));
            }
            db.SaveChanges();

        }
        catch (DbEntityValidationException e)
        {
            foreach (var eve in e.EntityValidationErrors)
            {
                Debug.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                    eve.Entry.Entity.GetType().Name, eve.Entry.State);
                foreach (var ve in eve.ValidationErrors)
                {
                    Debug.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                        ve.PropertyName, ve.ErrorMessage);
                }
            }
            throw;
        }
    }

    return Request.CreateResponse<Patient>(HttpStatusCode.Created, null);
}

【问题讨论】:

  • 您使用哪种方法/库进行 json 序列化?
  • 我们不使用 json 序列化只是 Web Api 到 json 对象到 poco 对象 c#?
  • 您进行了递归调用。创建一个单独的属性以进行转换。或者解压到其他地方
  • 你给 Web API 提供什么输入?应该由那个来确定。例如:2015-08-18T17:30:31Unspecified2015-08-18T17:30:31ZUtc2015-08-18T17:30:31+03:00Local
  • 你能解释更多吗?

标签: c# datetime


【解决方案1】:

您可以更改您的序列化程序设置以使用 JSON.net 序列化程序:

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = 
    new JsonSerializerSettings
    {
        DateFormatHandling = DateFormatHandling.IsoDateFormat,
        DateTimeZoneHandling = DateTimeZoneHandling.Unspecified,
    };

您还可以选择多种日期格式:DateTimeZoneHandling

/// <summary>
/// Specifies how to treat the time value when converting between string and <see cref="DateTime"/>.
/// </summary>
public enum DateTimeZoneHandling
{
    /// <summary>
    /// Treat as local time. If the <see cref="DateTime"/> object represents a Coordinated Universal Time (UTC), it is converted to the local time.
    /// </summary>
    Local = 0,

    /// <summary>
    /// Treat as a UTC. If the <see cref="DateTime"/> object represents a local time, it is converted to a UTC.
    /// </summary>
    Utc = 1,

    /// <summary>
    /// Treat as a local time if a <see cref="DateTime"/> is being converted to a string.
    /// If a string is being converted to <see cref="DateTime"/>, convert to a local time if a time zone is specified.
    /// </summary>
    Unspecified = 2,

    /// <summary>
    /// Time zone information should be preserved when converting.
    /// </summary>
    RoundtripKind = 3
}

【讨论】:

【解决方案2】:

您可以对此进行配置。见:http://www.newtonsoft.com/json/help/html/SerializeDateTimeZoneHandling.htm

这是一个例子:

public void Config(IAppBuilder app)
{
    var config = new HttpConfiguration();

    var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
    jsonFormatter.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;

    app.UseWebApi(config);
}

【讨论】:

    【解决方案3】:

    您可以使用 TimeZoneInfo.ConvertTime 转换为所需的时区。

    签出此方法: https://msdn.microsoft.com/en-us/library/bb382770(v=vs.110).aspx

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-16
      • 1970-01-01
      • 2014-04-30
      • 2017-03-28
      • 2020-12-16
      • 2018-11-04
      • 2018-05-04
      • 2019-11-11
      相关资源
      最近更新 更多