2013-04-04 86 views
5

從iPhone應用程序,我必須發送日期作爲參數到一個webservice方法,其中服務器解析邏輯用C#,.NET和JSON實現。從iphone應用程序發送日期時間到web服務

在我的iPhone應用程序,我格式化日期:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]]; 
[dateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"]; 
NSString *myDateString = [dateFormatter stringFromDate:SentOn]; 

我收到錯誤:

There was an error deserializing the object of type DashboardDataContract.Contracts.DashboardInputParams. DateTime content '2013-04-04T12:00:00Z' does not start with '/Date(' and end with ')/' as required for JSON.'.

我試圖日期的不同格式。在這方面有人能幫助我嗎?

回答

7

默認情況下,JSON.Net庫會發出使用ISO日期格式如"2012-05-09T00:00:00Z"所有日期,但微軟的JSON格式的日期會發出使用微軟自己的格式「/Date(xxxxxxxxxxxx)/」

你可以試試這個:

unsigned long long time=(([[NSDate date] timeIntervalSince1970])*1000); 
NSString* dateTimeTosend= [NSString stringWithFormat:@"/Date(%lld)/",time]; 
+0

非常好,簡單的創建一個類的方法! – user2068793 2013-04-04 11:54:08

+0

這是否可以在所有時區使用? – Anupdas 2013-04-04 12:03:52

+0

如果您想添加時區,您需要格式爲/ Date(xxxxxxxxxxxx + yyyy)/其中yyyy是時區,例如:/ Date(12345678954 + 0000)/ – 2013-04-04 12:06:35

0

將NSDate發送到服務器的最有效方法是獲取timestamp。你基本上可以用

NSTimeInterval timestamp = [[NSDate date] timeInvervalSince1970]; 
0

得到它可以在NSDate

- (NSString *)jsonDateString 
{ 
    NSTimeInterval seconds = [self timeIntervalSince1970]; 
    return [NSString stringWithFormat:@"/Date(%.0f+0000)/",seconds*1000]; 

} 
相關問題