NSTimeInterval format for POST with JSON objective

2019-08-13 15:42发布

问题:

I retrieve the NSTimeInterval as follows:

NSTimeInterval milisecondedDate = ([[NSDate date] timeIntervalSince1970] * 1000);

Which logs this: UNIX Timestamp: "1307710190993.865967"

I only want the value before the dot to send with JSON like this:

"/Date(1307710131826+0200)/"

Any suggestions?

Thanks in advance,

回答1:

Get the current timestamp in milliseconds since 1970 UNIX Timestamp.

NSTimeInterval millisecondedDate = ([[NSDate date] timeIntervalSince1970] * 1000);

Format the milliesecondedDate to a string with no decimals.

NSString* formattedMilliseconds = [NSString stringWithFormat:@"%.0f", millisecondedDate];

Set up the timestamp in DateTime .net format.

NSString *startOfDateFormat = @"/Date(";
NSString *endOfDateFormat = @"+0200)/";
NSString *dateTimeNow = [NSString stringWithFormat:@"%@%@%@",startOfDateFormat, formattedMilliseconds, endOfDateFormat];

There is probably a much better solution for doing this, but this worked for me for now.