c# serialized JSON date to ruby

大城市里の小女人 提交于 2020-01-13 13:53:02

问题


I have a C# application that serializes its DTOs to JSON and sends them accros the wire to be processed by Ruby. Now the format of the serialized date is like so:

/Date(1250170550493+0100)/

When this hits the Ruby app I need to cast this string representation back to a date/datetime/time (whatever it is in Ruby). Any ideas how I would go about this?

Cheers, Chris.


回答1:


You could parse out the milliseconds since the epoch, something like:

def parse_date(datestring)
  seconds_since_epoch = datestring.scan(/[0-9]+/)[0].to_i / 1000.0
  return Time.at(seconds_since_epoch)
end

parse_date('/Date(1250170550493+0100)/')

You'd still need to handle the timezone info (the +0100 part), so this is a starting point.




回答2:


You could use Json.NET to serialize your DTOs instead of the built in .NET JSON serializer. It gives you flexibility over how to serializing dates (i.e. as a constructor, ISO format, etc).




回答3:


.NET serializes in milliseconds from the epoch, so you need to divide the part before the timezone by 1000. Other wise your dates will be thousands of year off




回答4:


You can use Time.strptime to parse this to a Time object with the correct time zone:

Time.strptime(string, "/Date(%Q%z)/")

For example:

string = "/Date(1250170550493+0100)/"
Time.strptime(string, "/Date(%Q%z)/")
#=> 2009-08-13 14:35:50 +0100


来源:https://stackoverflow.com/questions/1272195/c-sharp-serialized-json-date-to-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!