iSee
iSee

Reputation: 604

Adding only date into core data as 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

Upvotes: 2

Views: 1130

Answers (2)

jrturton
jrturton

Reputation: 119242

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.

Upvotes: 3

Vladimir Gritsenko
Vladimir Gritsenko

Reputation: 1673

Two possible solutions, both not very pretty:

  1. Take the NSTimeInterval from the date, then truncate it down to the nearest 60*60*24 (seconds*minutes*hours). Something like interval = floor(interval - interval % (60*60*24)). Create a new date from that.
  2. Convert the date into a string showing only the date, then convert that string back to NSDate (might still have junk time components, though, but you can pad the string with 0 values).

Upvotes: 2

Related Questions