如何将日期转换为字符串

时间:2014-12-07 07:27:13

标签: ios objective-c nsdate nsdateformatter

我有字符串 - 12月13日,10:00 AM IST

如何将此字符串转换为任何人建议的日期?

我创建了这个日期格式化程序但是得到了null -

NSDateFormatter *userTimeFormatter = [[NSDateFormatter alloc] init];
[userTimeFormatter setDateStyle:NSDateFormatterMediumStyle];
[userTimeFormatter setTimeStyle:NSDateFormatterShortStyle];
userTimeFormatter.doesRelativeDateFormatting = YES;
[userTimeFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

1 个答案:

答案 0 :(得分:2)

NSDateFormatter *userTimeFormatter = [[NSDateFormatter alloc] init];
NSString *dateString = @"Dec 13, 10:00 AM IST";

NSTimeZone *timeZone = [NSTimeZone timeZoneWithAbbreviation:@"IST"];
[userTimeFormatter setTimeZone:timeZone];

dateString = [dateString stringByReplacingOccurrencesOfString:@" IST" withString:@""];
[userTimeFormatter setDateFormat:@"MMM d, hh:mm a"];

NSDate *date = [userTimeFormatter dateFromString:dateString];
NSLog(@"india date : %@", date);

这将为您提供IST TimeZone NSDate,从此日期开始您可以转换为系统时区:

[userTimeFormatter setTimeZone:[NSTimeZone systemTimeZone]];
NSDate *myDate = [userTimeFormatter dateFromString:dateString];
NSLog(@"my date : %@", myDate);

输出:

india date : 2000-12-13 04:30:00 +0000
my date : 2000-12-13 06:00:00 +0000