Search code examples
objective-cnsdatensnumber

How to send NSDate with a certain date format as NSNumber? i.e convert NSDate to NSDate with another format?


I have two user selected dates: startDate and endDate. They are NSDate instances and I have to send them as parameters as NSNumbers. How can I convert them to NSNumber with seconds?


Solution

  • 1) First, get the date in MM/dd/yyyy format:

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MM/dd/yyyy"];
    

    2) get string date and remove '/' from it:

    NString *string = [formatter stringFromDate:date];
    NString *finalStr = [string stringByReplacingOccurrencesOfString:@"/" withString:@""];
    

    3) Use NSNumberFormatter from converting NSString to NSNumber:

    NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
    f.numberStyle = NSNumberFormatterDecimalStyle;
    NSNumber *myNumber = [f numberFromString: finalStr];
    

    Hope, this is what you want!