You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Objective-C中日期字符串格式转换及日期拼接时间转日期问题

嘿,我来帮你搞定这两个Objective-C里的日期处理问题~

1. 如何在Objective-C中将日期字符串转换为另一种格式?

核心思路就是借助NSDateFormatter做两次转换:先把原日期字符串转成NSDate对象,再用目标格式把这个NSDate转成新的字符串。这里要注意格式匹配、时区和本地化的问题,不然容易出bug。

举个实际例子,假设你有一个yyyy-MM-dd HH:mm:ss格式的字符串,想转成dd/MM/yyyy的格式,代码可以这么写:

// 原日期字符串
NSString *originalDateStr = @"2024-05-20 14:30:00";

// 第一步:把原字符串转成NSDate
NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
// 一定要设置这个locale,避免不同地区的格式解析错误
[inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
NSDate *date = [inputFormatter dateFromString:originalDateStr];

// 第二步:把NSDate转成目标格式的字符串
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateFormat:@"dd/MM/yyyy"];
// 如果需要对应本地时区,可以设置成[NSTimeZone localTimeZone]
[outputFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
NSString *targetDateStr = [outputFormatter stringFromDate:date];

NSLog(@"转换后的日期:%@", targetDateStr); // 输出:20/05/2024
2. 日期选择器拼接时间转NSDate的代码修正

看了你给出的代码片段,里面有几个小问题:比如[fromDate fromString]是不存在的方法,还有时区设置不完整,逻辑也有点乱。我帮你整理了修正后的完整代码,顺便解释每一步:

// 假设fromdate是你的日期选择器对应的文本控件,它的文本格式是dd/MM/yyyy
NSString *selectedDateStr = fromdate.text;
// 拼接你需要的时间字符串,比如00:00:00
NSString *fullDateTimeStr = [NSString stringWithFormat:@"%@ 00:00:00", selectedDateStr];

// 初始化日期格式化器
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// 设置输入格式,必须和拼接后的字符串格式完全匹配
[dateFormatter setDateFormat:@"dd/MM/yyyy HH:mm:ss"];
// 同样设置locale避免解析失败
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
// 设置正确的时区,比如GMT或者你需要的具体时区,比如@"GMT+8"
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];

// 转换为NSDate对象
NSDate *currentDate = [dateFormatter dateFromString:fullDateTimeStr];

几个关键注意点:

  • 格式字符串@"dd/MM/yyyy HH:mm:ss"必须和拼接后的fullDateTimeStr格式完全一致,大小写和符号都不能错
  • en_US_POSIX这个locale一定要加,不然在一些非英文地区,系统可能会把日期格式解析错
  • 时区根据你的业务需求设置,如果要对应设备本地时间,可以改成[NSTimeZone localTimeZone]

内容的提问来源于stack exchange,提问作者Dinesh

火山引擎 最新活动