简体   繁体   中英

How to configure web api's json serializer to convert date time into ISO 8601 format?

I am working on web api project and inside my WebApiConfig class I have added this configuration to convert datetime parameters into ISO 8601 format:

  IsoDateTimeConverter converter = new IsoDateTimeConverter
        {
            //DateTimeStyles = DateTimeStyles.AdjustToUniversal,
            DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'"
        };

     config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(converter);

But if I pass in this value 2018-01-21T21:00:00.000Z from front-end side it does not convert it correctly into 2018-01-22 00:00:00.000

So, what's wrong with my configurations?

Don't need to use IsoDateTimeConverter just do:

var strDate = Convert.ToDateTime("2018-01-21T21:00:00.000Z").ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'", System.Globalization.CultureInfo.InvariantCulture);

it will give you 2018-01-22T00:30:00.000Z as I tested as your string format.

but you can change the format ;ike "yyyy'-'MM'-'dd' 'HH':'mm':'ss"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM