2013-03-15 79 views
3

我已經創建了一個將數據字符串寫入文本文件的方法。我想知道如何獲取系統日期和時間並將其發送到文本文件?下面是方法:獲取系統的日期和時間戳

-(void) writeToTextFile{ 

//get the documents dir 
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 

//file name to write the data to using the documents directory: 
NSString *fileName = [NSString stringWithFormat:@"%@/movbandlog.txt", 
         documentsDirectory]; 
//create content 
NSString *content = @"Data received from device\n \n \n \n \nData sent to Portal\n \n \n \n \nData received to Portal"; 

//save to documents directory 
[content writeToFile:fileName 
      atomically:NO 
      encoding:NSStringEncodingConversionAllowLossy 
       error:nil]; 

} 

回答

9

純可可

使用NSDate和可選NSDateFormatter對其進行格式化:

NSDate *currentDate = [NSDate date]; 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"dd.MM.YY HH:mm:ss"]; 
NSString *dateString = [dateFormatter stringFromDate:currentDate]; 
// NSLog(@"%@",dateString); 

// Adding your dateString to your content string 
NSString *content = [NSString stringWithFormat:@"Data received from device\n \n \n \n \nData sent to Portal\n \n \n \n \nData received to Portal\n \n \n \n \nData received at %@", dateString]; 

使用的Unix功能

你也可以考慮using unix functions for unlocalized日期(timest安培)

struct tm sometime; 
const char *formatString = "%Y-%m-%d %H:%M:%S %z"; 
(void) strptime_l("2005-07-01 12:00:00 -0700", formatString, &sometime, NULL); 
NSLog(@"NSDate is %@", [NSDate dateWithTimeIntervalSince1970: mktime(&sometime)]); 
// Output: NSDate is 2005-07-01 12:00:00 -0700 
+0

當然,平時的告誡 - 設置時區,如果你不想區域設置功能等 – 2013-03-15 01:00:02

+0

我怎麼會去加入這得到位是很重要的,設置的地點我NSString *內容?我需要在我的文本文件頂部列出日期和時間。 – TWcode 2013-03-15 01:23:58

+0

我已經更新了答案 – 2013-03-15 01:39:47