Converting Date to milli seconds in ios

1.6k views Asked by At

hi am using following to convert date to string in objective C.

-(void)convertDateToJsonString:(NSString *)strDate
{


    NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
    [formatter setTimeZone:[NSTimeZone systemTimeZone]];
    [formatter setLocale:[NSLocale systemLocale]];
    [formatter setDateFormat:@"yyyy/MM/dd"];


    NSDate * date =[formatter dateFromString:strDate];

    long long milliseconds = (long long)([date timeIntervalSince1970] * 1000.0);

    NSLog(@"After conversion %lli",milliseconds);



}

its giving date but always getting time is 00:00:00 something not current time.How to get selected date with current time in milli second.

but its working for current date like below

 long long millisecs = (long long)([[NSDate date] timeIntervalSince1970] * 1000.0);

    NSLog(@"After conversion %lli",millisecs);

Am getting from date picker date and converting.

And also for getting exact time zone like +530 in ios is there any methods? i know [NSTimezone Systemzone] but its giving whole value like "Asia/kolkatta +..."

2

There are 2 answers

2
GoZoner On

The problem is that your strDate is not getting parsed by dateFromString:. The result is that your date will be nil and timeInternvalSince1970 will do some default processing on nil. You can confirm this by adding:

NSAssert (nil != date);

after your initialize date. The assertion will fail.

The solution is that you need a better formatter - one that is consistent with the format of the passed in strDate.

But, perhaps you have a more fundamental problem. The UIDatePicker date property returns an NSDate object directly. Where are you getting your strDate from?

0
sanjaymathad On

You have not added hours, minutes and seconds in NSDateFormatter like this

[formatter setDateFormat:@"yyyy/MM/dd HH:mm:ss ZZZ"];