仅将日期作为 NSDate 添加到核心数据中
我有一个返回 JSON 对象的 Web 服务。响应包含 UNIX 时间戳(毫秒)格式的刷新时间。我通过以下代码将 UNIX 时间戳转换为 NSDate:
NSDate *date = [NSDate dateWithTimeIntervalSince1970:[[timeInUNIX objectAtIndex:i]doubleValue]/1000];
这给了我一个格式的时间
2009-11-13 19:47:49 +0000
,我只对这里的日期对象感兴趣。这很重要,因为日期在 NSSortDescriptor 中使用,并且也作为表视图中的节标题,因此我使用以下代码分隔日期和时间:
+ (NSDate *)dateWithOutTime:(NSDate *)datDate {
if( datDate == nil ) {
datDate = [NSDate date];
}
NSDateComponents* comps = [[NSCalendar currentCalendar] components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:datDate];
return [[NSCalendar currentCalendar] dateFromComponents:comps];
}
这里的问题是返回的 NSDate 对象仍然包含垃圾时间值。有没有办法只存储 NSDate 格式的日期?
有人可以帮我解决这个问题吗?
问候, 我懂了
I have a web service that returns a JSON object. The response consists of a refreshTime in UNIX timestamp (milliseconds) format. I convert the UNIX time stamp to NSDate by the following code:
NSDate *date = [NSDate dateWithTimeIntervalSince1970:[[timeInUNIX objectAtIndex:i]doubleValue]/1000];
This gives me a time in the format
2009-11-13 19:47:49 +0000
I am only interested in the date object here. This is important since the day is used in NSSortDescriptor and also as section header in tableview and hence I separate the date and time with the following code:
+ (NSDate *)dateWithOutTime:(NSDate *)datDate {
if( datDate == nil ) {
datDate = [NSDate date];
}
NSDateComponents* comps = [[NSCalendar currentCalendar] components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:datDate];
return [[NSCalendar currentCalendar] dateFromComponents:comps];
}
The problem here is the returned NSDate object still contains a junk time value. Is there any way to store only the date in NSDate format?
Can someone help me with this?
Regards,
iSee
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
NSDate 必须有一个时间 - 它是自参考日期以来的秒数,它代表特定的时间点。
如果您只对日/月/年部分感兴趣,处理此问题的正确方法是在显示日期时使用日期格式化程序或日期组件,而不是在存储日期时使用。或者,将日期存储为字符串,但这样您就会失去任何日期功能。
NSDate has to have a time - it is a number of seconds since a reference date, it represents a specific point in time.
If you are only interested in the day/month/year sections, the correct way to deal with this is to use a date formatter or date components when presenting the date, rather then when you store it. Alternatively, store the date as a string, but this way you lose any date functionality.
两种可能的解决方案,都不是很漂亮:
Two possible solutions, both not very pretty: