修剪 NSDate 以仅显示日期 [英] Trim NSDate to show date only
问题描述
我已经解决了所有类似的问题,不幸的是没有解决我的问题,所以我问了它.我需要我的函数返回一个 NSDate
和只有日期,但我的返回值也包含时间,我已经尝试了 setTimeStyle noStyle 和我能想出的所有可能的解决方案,这里是代码:
I have been through all the similar questions, unfortunately non could solve my problem so I asked it. I need my function to return an NSDate
and only date, but my return value contains timing as well, I have tried the setTimeStyle noStyle and every possible solution I could come up with, here is the code:
-(NSDate*)stringToDate{
NSString *dateString = @"01-02-2010";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *date;
date = [dateFormatter dateFromString:dateString];
NSLog(@"%@",date);
return date;
}
输出为:2010-01-31 16:00:00 +0000
我想要的:2010-01-31
推荐答案
这行不通,当您打印 NSDate 对象时,它将打印整个日期.从日期获取字符串表示的方式是使用 NSDateFormatter
This can't work, when you print a NSDate object it will print the ENTIRE date.
the way you get a string representation from a date is by using a NSDateFormatter
NSDateFormatter *format = [[NSDateFormatter alloc] init];
format.dateFormat = @"dd-MM-yyyy";
NSLog(@"%@", [format stringFromDate:[NSDate new]]);
如果你愿意,你可以把它放在 NSDate 的一个类别中.
you can put this in a category on NSDate if you so desire.
这篇关于修剪 NSDate 以仅显示日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!