1

I have a string like "20121124T103000" and I want to convert this to NSDate.

I tried converting it with dateFormatter date format "yyyyMMddThhmmss" but it gives output as 2001-01-01 00:00:00 +0000 which is incorrect.

What is the way we can convert this string to NSDate?

Here is my code:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyyMMddThhmmss"];
NSLog(@"%@",[dateFormat dateFromString:@"20121124T103000"]);

Any help is appreciated.

Virja Rahul
  • 415
  • 2
  • 4
  • 12
Hrushikesh Betai
  • 2,227
  • 5
  • 33
  • 63
  • possible duplicate of [Proper way to convert NSString to NSDate on iOS?](http://stackoverflow.com/questions/6892587/proper-way-to-convert-nsstring-to-nsdate-on-ios) – Midhun MP Nov 24 '12 at 10:21

3 Answers3

4

Your original code is quite close; instead of:

@"yyyyMMddThhmmss"

You should be using:

@"yyyyMMdd'T'hhmmss"

The only difference is the pair of single quotes around the 'T' in the string- you just need to let the app know that 'T' is a part of the formatting, not the actual date.

username tbd
  • 9,152
  • 1
  • 20
  • 35
1

Try the following Code.

NSString *dateStr = @"20121124T103000";
    NSDateFormatter *dtF = [[NSDateFormatter alloc] init];
    [dtF setDateFormat:@"yyyyMMdd'T'hhmmss"];
    NSDate *d = [dtF dateFromString:dateStr];
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyyMMdd'T'hhmmss"];
    NSString *st = [dateFormat stringFromDate:d];   
NSLog(@"%@",st]);
Siba Prasad Hota
  • 4,779
  • 1
  • 20
  • 40
1

do like this,

NSString *dateStr = @"20121124T103000";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyyMMdd'T'hhmmss"];
NSDate *d = [dateFormat dateFromString:dateStr];
NSString *st = [dateFormat stringFromDate:d];   
NSLog(@"%@",st);
Venk
  • 5,949
  • 9
  • 41
  • 52
  • Also consider setting the `locale` and `timeZone` as suggested in [Apple Technical Q&A 1480](https://developer.apple.com/library/ios/qa/qa1480/_index.html). – Rob Oct 22 '14 at 14:42