gpt4 book ai didi

objective-c - 获取系统的日期和时间戳

转载 作者:太空狗 更新时间:2023-10-30 03:48:57 25 4
gpt4 key购买 nike

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

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

}

最佳答案

纯 cocoa

使用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日期(时间戳)

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

关于objective-c - 获取系统的日期和时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15422848/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com