我是 iOS(Objective-c) 编码的新手,我被时间戳困住了。
我在解析 JSON 时获取时间戳,即 2017-04-30T14:30+00:00(GMT)
。如何从此时间戳获取日期、小时、分钟和秒?我在 GMT
中得到这种格式,所以,是否可以将其转换为 "IST"
?怎么办?
最佳答案
日期格式模式
日期模式是一串字符,其中特定字符串在格式化时被替换为日历中的日期和时间数据,或者在解析时用于为日历生成数据。以下是模式中使用的字符,用于显示给定区域设置的适当格式。以下是示例:
- (NSString *)curentDateStringFromDate:(NSDate *)dateTimeInLine withFormat:(NSString *)dateFormat {
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:dateFormat];
NSString *convertedString = [formatter stringFromDate:dateTimeInLine];
return convertedString;
}
像下面这样使用它:
NSString *dateString = [self curentDateStringFromDate:[NSDate date] withFormat:@"dd-MM-yyyy"];
NSString *timeString = [self curentDateStringFromDate:[NSDate date] withFormat:@"hh:mm:ss"];
NSString *hoursString = [self curentDateStringFromDate:[NSDate date] withFormat:@"h"];
在 Foundation 框架
中,用于此任务(在任一方向)的类是 NSDateFormatter
Refer here
下面的代码将 GMT 转换为 IST。
NSString *inDateStr = @"2000/01/02 03:04:05";
NSString *s = @"yyyy/MM/dd HH:mm:ss";
// about input date(GMT)
NSDateFormatter *inDateFormatter = [[NSDateFormatter alloc] init];
inDateFormatter.dateFormat = s;
inDateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
NSDate *inDate = [inDateFormatter dateFromString:inDateStr];
// about output date(IST)
NSDateFormatter *outDateFormatter = [[NSDateFormatter alloc] init];
outDateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"IST"];
outDateFormatter.dateFormat = s;
NSString *outDateStr = [outDateFormatter stringFromDate:inDate];
// final output
NSLog(@"[in]%@ -> [out]%@", inDateStr, outDateStr);
关于ios - 如何在 Objective-c 中从时间戳 "2017-04-30T14:30+00:00(GMT)"获取日期、小时、分钟和秒?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43229913/