locked
JSON Serialization date format not working RRS feed

  • Question

  • User565442435 posted

    So I have a class I created to give me a specific date format when I serialize an object.

    	public class IssueDateFormat : IsoDateTimeConverter
    	{
    		public IssueDateFormat()
    		{
    			base.DateTimeFormat = "yyyy-MM-dd HH:mm:ss K";
    		}
    	}

    Then I have a property like so

    [JsonConverter(typeof(IssueDateFormat))]
    public DateTime issued_at { get; set; }

    Now, if I set obj.issued_at to Datetime.Now I get the proper date format 2017-03-09 09:58:31 -06:00 in the json string. However, if I set it to my database datetime value, I get 2017-03-09 09:58:31 

    Any ideas why when it takes a date from the database, it doesn't add the -06:00 on the end?

    Edit

    I want to add I just discovered that if I do

    DateTime dt = new DateTime(exam.exam_date_time.Year, exam.exam_date_time.Month, exam.exam_date_time.Day, exam.exam_date_time.Hour, 
    					exam.exam_date_time.Minute, exam.exam_date_time.Second, exam.exam_date_time.Millisecond, DateTimeKind.Local);
    
    badge.issued_at = dt;

    Then I do get the -06:00 on the end, my question is, how could I handle that in the property in my object class so that it automatically does that. 

    Thursday, March 9, 2017 4:10 PM

Answers

  • User565442435 posted

    I found the solution, if I set base.DateTimeStyles = DateTimeStyles.AssumeLocal; in my IssueDateFormat class, that fixes it.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, March 10, 2017 2:42 PM

All replies

  • User-2057865890 posted

    Hi Mandrews1234,

    If you want to store all timezone information on the server you can:

    1. Declare your WEB API 2 Date types with the "DateTimeOffset" type.

    2. Finally store your dates within the database using the "datetimeoffset" type.

    reference: https://msdn.microsoft.com/en-us/library/bb630289.aspx

    Best Regards,

    Chris

    Friday, March 10, 2017 5:53 AM
  • User565442435 posted

    I found the solution, if I set base.DateTimeStyles = DateTimeStyles.AssumeLocal; in my IssueDateFormat class, that fixes it.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, March 10, 2017 2:42 PM