Why is Time.strptime() returning the current date?

2019-07-04 05:00发布

Making a GET request to a private (no public documentation) API returns data in JSON format.

The value im interested in is the date. It returns the date in ASP.NET JSON Date format. Here's what it looks like:

AanmeldDatum: "/Date(1406675114000+0200)/"

There's another variable called AangebodenSindsTekst which means OfferedSinceText and it's value is "8 augustus 2014". So the unknown Date format should get parsed into that specific value.

I've tried this:

require 'time'

foo = Time.strptime('1406675114000+0200', '%N') # => 2014-08-12 13:38:46 +0200
foo = Time.strptime('1406675114000+0200', '%N%z') # => 2014-08-12 14:38:58 +0200

But it simply returns the current time.

I know 100% sure that /Date(1406675114000+0200)/ when parsed, should return the date 2014-07-30.

The question is how do I make sure it does?

1条回答
Deceive 欺骗
2楼-- · 2019-07-04 05:47

Using '%N' or '%N%z' seems to trigger a bug in strptime, resulting in the current date/time:

Time.strptime('1262300400000+0100', '%N') # => 2014-08-14 16:30:01 -0700
Time.strptime('1262300400000+0100', '%N%z') # => 2014-08-14 08:30:01 -0700

Using '%Q%z' parses to:

Time.strptime('1262300400000+0100', '%Q%z') # => 2010-01-01 00:00:00 +0100

The Time.strptime documentation doesn't mention '%Q', but the DateTime.strptime doc does.

If you have parsed the date string, then formatting it is easy:

foo = Time.strptime('1262300400000+0100', '%Q%z') # => 2010-01-01 00:00:00 +0100
foo.strftime('%Y-%m-%d %H:%M:%S %z') # => "2010-01-01 00:00:00 +0100"

See the strftime documentation for more information about your formatting options.

Notice that there are some shortcuts for things like '%Y-%m-%d' and '%H:%M:%S':

foo.strftime('%F %T %z') # => "2010-01-01 00:00:00 +0100"

The real problem is how .NET is serializing the date in JSON. A search of the googles shows a number of pages talking about this:

.NET isn't alone in doing this. Ruby's JSON and YAML serializers will occasionally do similar things, and the fix is to look at the JSON being output, and then provide to_json or to_s or to_h handlers that will result in JSON output that best represents the data. JSON is supposed to be transferable between JavaScript and backend systems, and .NET isn't the only language offering that capability. Perl, Ruby, Python, and who knows how many other languages can parse and emit JSON, and they all need to play by the same rules.

查看更多
登录 后发表回答