5

我创建了一种将数据字符串写入文本文件的方法。我想知道如何获取系统日期和时间并将其发送到文本文件?这是方法:

 -(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];

}
4

1 回答 1

10

纯可可

使用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 函数

您也可以考虑将 unix 函数用于未本地化的日期(时间戳)

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
于 2013-03-15T00:55:38.620 回答