Reputation: 13329
Im trying to send an api a asp.net UTC timestamp like this:
d = new Date()
test = moment(d).utc().valueOf()
test2 = moment(d).utc().format("ZZ")
utc_asp = "/Date("+test+test2+")/"
console.log utc_asp
>> /Date(1372670700799+0000)/
But the time the server gets is the same as local time?
Or this:
console.log moment(d)
console.log moment(d).utc()
D {_i: Mon Jul 01 2013 11:26:10 GMT+0200 (SAST), _f: undefined, _l: undefined, _isUTC: false, _d: Mon Jul 01 2013 11:26:10 GMT+0200 (SAST)…}
index.js:39
D {_i: Mon Jul 01 2013 11:26:10 GMT+0200 (SAST), _f: undefined, _l: undefined, _isUTC: true, _d: Mon Jul 01 2013 11:26:10 GMT+0200 (SAST)…}
doing this:
console.log moment(now).utc().hour()
>> 9 - This is correct! Its 11 - 2, but how come the above
Am I doing it incorrect?
Upvotes: 4
Views: 817
Reputation: 241475
To create a moment from the current date, just use moment()
without any parameters.
var m = moment(); // returns a moment representing "now"
If you then want to format it with the MS proprietary /Date()/
format, you can use:
m.format("/[Date](XSSS)/")
This will give you a value such as /Date(1372728650261)/
which is suitable for passing to .Net and will ultimately give you a DateTime
object where .Kind
is Utc
.
If you want the extended format with the offset, you can use this:
m.format("/[Date](XSSSZZ)/")
And it will give you back a value such as/Date(1372728650261-0700)/
. This matches the requirements of the DataContractJsonSerializer
class in .Net. See the section titled "DateTime Wire Format" in these docs.
However, I strongly recommend you do not use this latter format. It's only recognized by DataContractJsonSerializer
and the docs explicitly state that whatever offset you provide will be ignored - using the server's own offset instead. That's rather silly, but that's what it does. If you are using JavaScriptSerializer
class, the offset is also ignored, but it has different behavior than DCJS (staying with UTC instead of going local).
For that matter, I would recommend abandoning this strange format completely. Use the ISO8601 standard instead (example, 2013-07-01T18:38:29-07:00
). This is easily done with momentjs and is the default format.
moment().format() // it's the default, no need to specify anything.
On the server side, use JSON.Net, which also uses this format by default. And if you actually care about the offset, use the DateTimeOffset
type on the server instead of the DateTime
type.
Upvotes: 2
Reputation: 891
I'm not sure but try check if your asp.net Datetime use localtime, utc or unspecified for deserialization.
Upvotes: 0