获取系统日期和时间戳

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

}
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

当然,通常的警告 - 如果时区很重要,请设置时区;如果您不想受到语言环境特性的影响,请设置语言环境。 - Hot Licks
我该如何将这个添加到我的NSString *content中?我需要在文本文件顶部列出日期和时间。 - TWcode
在您的Unix函数中,我有两个问题:1.strptime_l方法会抛出一个警告,尽管我已经包含了<time.h>,如何解决?2.输出的日期是像您在strptime_l方法中编码的那样吗?如何输出当前时间?谢谢。 - Guo Luchuan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接