2011-06-27 30 views
1
NSDate *My_StartDate,*My_EndDate ; 
NSDateFormatter * df= [[NSDateFormatter alloc]init]; 
[df setDateFormat:@"dd/MM/yyyy hh:mm:ss"]; 
My_StartDate = [df dateFromString:@"01/05/2010 10:15:33"]; 
My_EndDate = [df dateFromString:@"01/05/2010 10:45:33"]; 
NSLog(@"%@",My_StartDate); 
NSLog(@"%@",My_EndDate); 

在日誌中,我爲my_startdate得到類似於2010-05-01 04:45:33 +0000和結束日期爲2010-05-01 05:15的情況:33 +0000,而不是我應該得到的值作爲開始日期爲2010-05-01 10:15:33 +0000和結束日期爲2010-05-01 10:45:33 +0000從字符串設置nsdate值時出現問題

+0

貌似時區問題 – Krishnabhadra

+0

u能解釋我到底想要什麼? – Tendulkar

回答

1

請嘗試以下功能:

-(NSString *)getDateStringFromDate :(NSDate *)dateValue{ 
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
[dateFormat setDateFormat:@"yyyy-MM-dd"]; 

NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init]; 
[timeFormat setTimeStyle:NSDateFormatterShortStyle]; 

[timeFormat setDateFormat:@"HH:mm:ss"]; 
//[timeFormat setDateFormat:@"HH:mm"]; 
//[timeFormat setDateFormat:@"HH:mm a"];  
////  

NSString *theDate = [dateFormat stringFromDate:dateValue]; 
NSString *theTime = [timeFormat stringFromDate:dateValue]; 

NSLog(@"\n"   
"theDate: |%@| \n" 
"theTime: |%@| \n" 
, theDate, theTime); 

return theDate; 
} 

根據您的需要更改數據格式。

如有任何困難,請告知我。

乾杯。

0

它顯示asper GMT + 4.30 time.It只顯示那樣。當你使用DateFormatter將該日期轉換爲字符串時,它給出了相同的日期(無論你想要開始日期爲01/05/2010 10 :15:33,截止日期爲01/05/2010 10:45:33)。

NSDateFormatter * dateformatter= [[NSDateFormatter alloc]init]; 
[dateformatter setDateFormat:@"dd/MM/yyyy hh:mm:ss"]; 
NSString *dat = [dateformatter stringfromDate:My_StartDate]; 

,那麼你將得到的輸出爲01/05/2010 10點15分33秒

0

這顯示了美國遵循的標準時間字符串的日期,但這個原因,你沒有做出任何得到問題您logic.Also

[df setDateFormat:@"dd/MM/yyyy hh:mm:ss"]; 

這種格式使用12個小時格式(指下午2時03分和2:03)和Date對象從不使用AM和PM用於顯示日期對象的值,但是當你正確地轉換它,然後它給你正確的日期和時間。

如果您覺得遇到任何問題,請使用不同的語言環境。

0

您可能需要在此處將日期格式化程序的時區設置爲GMT。做它使用

[df setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]]; 

之前你做dateFromString:調用。這會給你你想要的。

0

只需要在這裏更新您的代碼:

我可能會像你的時間是24小時制,所以這時候你需要使用這個....比其他你需要設置時區。

請點擊此鏈接爲所有區:http://unicode.org/reports/tr35/tr35-6.html#Date%5FFormat%5FPatterns

[df setDateFormat:@"dd/MM/yyyy hh:mm:ss"]; 
to 
[df setDateFormat:@"dd/MM/yyyy HH:mm:ss"]; 

你做;)