2015-08-18 12 views
8

Ho problemi quando ho datatime in json object lo convertirò in fuso orario UTC in C# dateTime voglio solo chiedere come mantenere l'ora locale? Posso impostare la proprietà del fuso orario nel file web.config o geter o setter perché I devono poter obiettare avere il giorno e l'ora? questo è un esempio di classe?conserva l'ora locale datetime C# tra json e Web API?

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; } 
} 

aggiornamento ho cercato di utilizzare getter e setter per risolvere ho questa eccezione {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); 
} 
+1

Quale metodo/biblioteca stai usando per la serializzazione JSON? – Xiaoy312

+0

non stiamo usando serializzazione json solo Web Api su json object su poco oggetto C#? –

+1

Hai effettuato una chiamata ricorsiva. Creare una proprietà separata per la conversione. Oppure estraila in un posto diverso. – Artiom

risposta

9

È possibile modificare le impostazioni serializzatore di utilizzare il serializzatore JSON.net:

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

C'è anche vari formato della data è possibile scegliere tra: 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 
} 
+0

Mi hai battuto per questo. Ecco la documentazione ufficiale: http://www.newtonsoft.com/json/help/html/SerializeDateTimeZoneHandling.htm –

2

È possibile configurarlo. Vedi: http://www.newtonsoft.com/json/help/html/SerializeDateTimeZoneHandling.htm

Ecco un esempio:

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

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

    app.UseWebApi(config); 
}