0

I am getting the date from database in Milliseconds format.I am convrting that date in to the normal date format.But it returns wrong date.Once please give me the solution in ios

The date in milliseconds is 1385856000000

After convert that date i am getting 10/26/1970.

But real date is 12/1/2013 .

I am using the following code is

int dobint = [secondChangeDob intValue];

            NSTimeInterval timeInSecond = dobint/1000;

            NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInSecond];

            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"MM/dd/yyyy"];
            NSString *formattedDate=[formatter stringFromDate:date];
            NSLog(@"Formatted Date : %@",formattedDate);
            NSUserDefaults *dateDef = [NSUserDefaults standardUserDefaults];
            [dateDef setObject:formattedDate forKey:@"bDATE"];

3 Answers3

6

Your secondChangeDob as an int won't work with such a value, as an int is simply too small to hold the value you are storing in an NSNumber.

NSTimeInterval is of type double so you could try -

NSTimeInterval timeInSecond = [secondChangeDob doubleValue]/1000.0;

NSNumber has a method that will return a double named doubleValue. The above code returns secondChangeDob as a double so as no type casting issues arise when storing the result as an NSTimeInterval.

Bamsworld
  • 5,670
  • 2
  • 32
  • 37
2

the int is too small to hold 1385856000000

so the number gets corrupted

use e.g. an unsigned long long or just double

Daij-Djan
  • 49,552
  • 17
  • 113
  • 135
  • I'd suggest replacing it with NSInteger. – Milo Jan 11 '14 at 10:40
  • also don't forget to replace the call to intValue. – Daij-Djan Jan 11 '14 at 10:42
  • i'd use unsigned as it is an unsigned value – Daij-Djan Jan 11 '14 at 10:44
  • An unsigned long gives a warning, it actually should be a long long – Milo Jan 11 '14 at 10:45
  • 1
    Speaking about integer types, int, unsigned int, long, unsigned long are all the same size - 4 bytes on 32-bit iOS devices. It’s only on 64-bit devices where int and long differ. So to fit the value on both architectures, one of “long long” types or double should be used. – eofster Jan 11 '14 at 13:34
  • NSUInteger is unsigned int on 32-bit, so it is 4 bytes there. And unsigned long on 64 bit, so it is 8 bytes there. – eofster Jan 11 '14 at 13:36
-1

You can do it like this :

NSDate *myDate = [NSDate dateWithTimeIntervalSince1970:1385856000000];

and

NSDate *myDate = [NSDate dateWithTimeIntervalSinceReferenceDate:1385856000000];

and

NSDate *myDate = [NSDate dateWithTimeIntervalSinceNow:1385856000000];

Zeeshan
  • 4,194
  • 28
  • 32