所有
我有一个从数据库中获取日期(YYYY-MM-DD H:M:S)的方法,并使用日期字符串中的年,月和日组件创建一个URL。我的解决方案有效,但我想知道是否有更好的方法来做到这一点?凉爽的孩子们如何做到这一点? : - )
谢谢!
-(NSString *) prettyURLFrom:(NSString *)dateString{
NSString * URLString = @"";
NSString *URL = @"http://www.theblues.com/featured/article/";
NSArray *myWords = [dateString componentsSeparatedByCharactersInSet:
[NSCharacterSet characterSetWithCharactersInString:@"-\" \" :"]
];
URLString = [NSString stringWithFormat:@"%@%@/%@/%@",
URL,
[myWords objectAtIndex:1],
[myWords objectAtIndex:2],
[myWords objectAtIndex:0]];
return URLString;
}
答案 0 :(得分:1)
如果您有NSDate
个对象,则可以使用
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:date];
NSInteger day = [components day];
NSInteger month = [components month];
NSInteger year = [components year];
NSString到NSDate
[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehavior10_4];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"YYYY-MM-DD HH:MM:SS"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:@"1999-07-02 2:2:4"];
答案 1 :(得分:1)
就像我在评论中所说的那样,我发现你传递的值很奇怪,并且当它们可能分别是NSDate和NSURL时,将值作为字符串返回。
我可能会这样做:
-(NSURL*)URLFromDate:(NSDate*)date
{
// Assumes user uses a gregorian calendar
NSDateComponents *dateComp = [[NSCalendar currentCalendar] components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:date];
return [NSURL URLWithString:[NSString stringWithFormat:@"http://www.theblues.com/featured/article/%li/%li/%li"
, [dateComp year]
, [dateComp month]
, [dateComp day]]];
}