2

I am converting this date string "05/20/2015 05:27 pm" into NSDate with the help of formatter but it returns nil.

-(NSDate *)dateFromString:(NSString *)strDate withFormat:(NSString *)strDateFormat
{
NSDate *date = nil;

[self.dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
if (strDate) {
    if (strDateFormat) {
        [self.dateFormatter setDateFormat:strDateFormat];

    }

    date = [self.dateFormatter dateFromString:strDate];

}
return  date;
}

I am using the above function where I am passing the string as "05/20/2015 05:27 pm" with format @"dd/MM/yyyy HH:mm:ss".

Bhumit Mehta
  • 16,278
  • 11
  • 50
  • 64
Faran Ghani
  • 277
  • 4
  • 17

5 Answers5

1
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"mm/dd/yyyy hh:mm a"];
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
NSDate *stringDate = [dateFormatter dateFromString:@"05/20/2015 05:27 pm"];
NSLog(@"%@", stringDate);
VD Patel
  • 286
  • 1
  • 6
1
-(NSDate *)dateFromString:(NSString *)strDate withFormat:(NSString *)strDateFormat
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:strDateFormat];

    [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
    NSDate *date = [dateFormatter dateFromString:strDate];
    return date;

}
Dharmesh Dhorajiya
  • 3,976
  • 9
  • 30
  • 39
  • there is no problem with the function, I am passing a wrong format . this format helps "mm/dd/yyyy hh:mm a" given by @VD Patel – Faran Ghani May 20 '15 at 12:23
0
NSString *dateStr = @"05/20/2015 05:27 pm";

// Convert string to date object

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];

[dateFormat setDateFormat:@"dd-MM-yyyy HH:mm:ss Z"];

NSDate *date = [dateFormat dateFromString:dateStr]; 

Nslog(@"%@",date);
Dharmesh Dhorajiya
  • 3,976
  • 9
  • 30
  • 39
Nikunj
  • 280
  • 3
  • 15
0

To transform from NSDate to timestamp you can use:

NSDate *date = [NSDate date];
NSTimeInterval timestampSeconds = [date timeIntervalSince1970];

Result will be in seconds. To transform timestamp to standard milliseconds just multiply by 1000.

Dima Cheverda
  • 402
  • 1
  • 4
  • 10
0

timeIntervalSince1970

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"mm/dd/yyyy hh:mm a"];
NSDate *strDate = [formatter dateFromString:@"05/20/2015 05:27 pm"];
NSLog(@"%@", strDate);//NSDate
time_t timeStamp = (time_t) [strDate  timeIntervalSince1970];
NSLog(@"%ld", timeStamp);//timestamp

How to convert NSDate into unix timestamp iphone sdk?

This might helps you :)

Community
  • 1
  • 1
Yuyutsu
  • 2,509
  • 22
  • 38