2016-05-09 29 views
-2

我使用NSOutputStream將數據從客戶端(IOS設備)輸出到服務器(PC設備)。 在下面的代碼我使用1.4.3和OutputStream的一些數據(此代碼的工作100%)IOS:將NSDate對象轉換爲字符串以獲取當前時間

NSString *response = @" Today's Sunny \n "; 
NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSASCIIStringEncoding]]; 
[outputStream write:[data bytes] maxLength:[data length]]; 

我想這樣做使用的OutputStream輸出電流時一樣(09一樣的東西: 24.00)這種格式(HH:MM:SS)

這裏是我曾嘗試

NSDate *currentTime = [NSDate date]; 
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init]; 
    [formatter setDateFormat:@"hh:mm:ss"]; 
    //outputstream here 

我會很感激你的幫助,在這個問題上

+0

因此,一個'NSDateFormatter'格式的問題嗎? – trojanfoe

+0

@trojanfoe是的,我試圖使用outputstream輸出NSDateFormatter中的當前時間。 –

+2

在這個網站上有成千上萬的問題。你也需要改變你的問題,因爲它與'NSOutputStream'無關。 – trojanfoe

回答

1

您需要將日期轉換爲字符串,然後將其添加到輸出流。

用途:

NSDate *currentTime = [NSDate date]; 
NSDateFormatter *formatter = [[NSDateFormatter alloc]init]; 
[formatter setDateFormat:@"hh:mm:ss"]; 
NSString *timeString = [formatter stringFromDate:currentTime]; 

然後,您可以在您的輸出流發送TIMESTRING

+0

你有什麼問題可以幫我解決這個問題嗎?http://stackoverflow.com/questions/37141410/ios-how-to-reconnect-to-the-server-pc-after-its-got-disconnected –

-2

下面是完整的答案,由於@Adam

NSDate *currentTime = [NSDate date]; 
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init]; 
    [formatter setDateFormat:@"hh:mm:ss"]; 
    NSString *timeString = [formatter stringFromDate:currentTime]; 
    [outputStream write:[timeString UTF8String] 
       maxLength:[timeString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]]; 
+0

12小時時鐘?那是你想要的嗎? – trojanfoe

+0

@trojanfoe是的,時間格式是12小時 –

0

如果有人需要阿薩姆邦的代碼+亞當在斯威夫特,這裏是:

var currentTime:NSDate = NSDate.date() 

var formatter:NSDateFormatter = NSDateFormatter.alloc().init() 
formatter.setDateFormat("hh:mm:ss") 

var timeString:NSString = formatter.stringFromDate(currentTime) 
outputStream.write(timeString.UTF8String(),maxLength:timeString.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)) 
1

看看這個,它有您需要了解最新的編程iOS上 http://rypress.com/tutorials/objective-c/data-types/dates

更新一些代碼樣本的一切:

從NSDate的電流轉換時間的NSString:

NSDate *currentTime = [NSDate date]; 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 

[dateFormatter setCalendar:[NSCalendar currentCalendar]]; 
[dateFormatter setTimeZone:[NSTimeZone defaultTimeZone]]; 
[dateFormatter setDateFormat:@"M.d.y"]; 

NSString *stringResult = [dateFormatter stringFromDate:currentTime]; 

設置CalendarTimeZone是可選的,但如果需要可以使用它們。你也有不同的選配對他們來說,就像NSCalendarIdentifierGregoriantimeZoneForSecondsFromGMT:

您有dateFormat很多選擇,例如

M/d/Y - > 2012年11月4日

MM/DD/YY - > 12年11月4日

MMM d, '' YY - > 11月4日,'12

H:毫米 - >下午8時09

或者,您可以改用dateStyletimeStyle

[dateFormatter setDateStyle:NSDateFormatterMediumStyle]; 
[dateFormatter setTimeStyle:NSDateFormatterShortStyle]; 
+0

雖然這個鏈接可能回答這個問題,但最好在這裏包含答案的重要部分,並提供參考鏈接。如果鏈接頁面更改,則僅鏈接答案可能會失效。 - [來自評論](/ review/low-quality-posts/12294505) – Eiko

+0

@Eiko好的。更新了一些代碼示例和解釋 – Stephenye

相關問題