0

How to convert Datetime timestamp to a NSDate? How to make the inverse?

My method to convert datetime to a string :

+(NSString*) dateTojson:(NSDate*)date{

    return [NSString stringWithFormat:@"/Date(%f)/",(double)([date dateWithTimeIntervalSince1970] * 1000)];
}

My inverse method:

+(NSDate*) jsonToDate:(NSString *)json
{
    double milisec = 0;
    json = [[[json stringByReplacingOccurrencesOfString:@"/Date(" withString:@""] stringByReplacingOccurrencesOfString:@"/" withString:@""] stringByReplacingOccurrencesOfString:@"-0200" withString:@""];
    NSArray *arr = [json componentsSeparatedByString:@"-"];
    for(NSString *s in arr) {
        if(![s isEqualToString:@""]){
            milisec += [s doubleValue];
        }
    }

    NSDate *date = [NSDate dateWithTimeIntervalSince1970:(milisec / 1000.0)];

    return date;
}

When i use [self jsonToDate:@"/Date(1495497600)/"] where 1495497600 represents "05/23/2017", the method return me a wrong date (result = "01/18/1970"). Why?

Notes:

i'm not considering the time, only date. My variable milisec is equals to 1495497600, so i think the problem is the method dateWithTimeIntervalSince1970.

already try some posts like:

Convert milliseconds to NSDate

How to Convert a milliseconds to nsdate in objective C

1 Answers1

1

You don't really need to divide the milliseconds at the end:

NSDate *date = [NSDate dateWithTimeIntervalSince1970:milisec];

Result:

2017-05-23 00:00:00 +0000
l'L'l
  • 44,951
  • 10
  • 95
  • 146
  • Thanks, that works, but why dont need to divide to 1000 and either multiply in other method? This give the difference, and all answers in stack say that need to do this. Anyway, thanks again. – Juan Munhoes Junior May 24 '17 at 02:07
  • It's because your time is already in seconds, not milliseconds, so when you divide it by 1000 you'll end up with approximately 18 days starting from 1/1/1970. – l'L'l May 24 '17 at 03:57
  • 1
    1495497600 seconds / 1000 milliseconds = 1.495×10^9 milliseconds since 1/1/1970 = 01/18/1970. – l'L'l May 24 '17 at 04:18