我从我的服务器获取日期字符串,如“10/4/2013 10:00:00 PM”。现在我只想在我的标签上显示几个小时。但问题是我使用的是以下代码但没有获得实际时间。
-(NSString*)convert:(NSString*)strdate
{
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
[formatter setLocale:[NSLocale systemLocale]];
[formatter setDateFormat:@"dd/MM/yyyy HH:mm:ss a"];
NSDate * date = [formatter dateFromString:strdate];
NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setDateFormat:@"hh:mm"];
NSString *depResult = [df stringFromDate:date];
NSLog(@"hours %@ ", [df stringFromDate:date]);
return depResult;
}
并将字符串输入作为“10/4/2013 9:00:00 PM”并输出为“05:30”。请更正我的位置我做错了。谢谢
答案 0 :(得分:11)
+(NSString *)getDateStringFromDate :(NSDate *)date {
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"dd/MM/yyyy hh:mm:ss a"];
NSString *dateString = [dateFormatter stringFromDate:date];
return dateString;
}
+(NSDate *)getDateFromDateString :(NSString *)dateString {
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"dd/MM/yyyy hh:mm:ss a"];
NSDate *date = [dateFormatter dateFromString:dateString];
return date;
}
答案 1 :(得分:2)
如果您有来自服务器的此日期"10/4/2013 9:00:00 pm"
,
如果你想要的输出是02:24 AM
然后你需要做这样的事情。
-(NSString*)convert:(NSString*)strdate
{
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
[formatter setLocale:[NSLocale systemLocale]];
[formatter setDateFormat:@"dd/MM/yyyy hh:mm:ss a"];
NSDate * date = [formatter dateFromString:strdate];
NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setDateFormat:@"hh:mm a"];
NSString *depResult = [df stringFromDate:date];
NSLog(@"hours %@ ", [df stringFromDate:date]);
return depResult;
}
答案 2 :(得分:2)
使用以下代码:
- (NSString *)convert:(NSString *)strdate
{
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
[formatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
[formatter setDateFormat:@"dd/MM/yyyy hh:mm:ss a"];
NSDate * date = [formatter dateFromString:strdate];
NSDateFormatter * df = [[NSDateFormatter alloc] init];
[df setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
[formatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
[df setDateFormat:@"hh:mm"];
NSString * depResult = [df stringFromDate:date];
NSLog(@"hours %@ ", [df stringFromDate:date]);
return depResult;
}