3

I have the following code which is simply getting the current date and converting it to the format YYYY-MM-dd HH:mm:ss zzz

        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat: @"YYYY-MM-dd HH:mm:ss zzz"];
        NSTimeZone *currentTimeZone = [NSTimeZone localTimeZone];
        [dateFormatter setTimeZone:currentTimeZone];

        NSString *time = [dateFormatter stringFromDate:[NSDate date]];

        NSLog(@"TIME IS %@", time);

With this, I'm getting the following log output:

2014-12-30 00:20:38.987 MYAPPNAME[953:229825] TIME IS 2015-12-30 00:20:38 CST

Can someone tell me why the output is showing as 2015, rather than 2014 as it should be?

Mrunal
  • 13,982
  • 6
  • 52
  • 96
AdamTheRaysFan
  • 175
  • 2
  • 9

3 Answers3

5

yyyy specifies the calendar year, whereas YYYY specifies the year (of “Week of Year”)

you must change your dateformatter style from

[dateFormatter setDateFormat: @"YYYY-MM-dd HH:mm:ss zzz"];

to

[dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss zzz"];

for your reference, check this apple documentation

arthankamal
  • 6,341
  • 4
  • 36
  • 51
1

change your date formate

[dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss zzz"];
Anil Varghese
  • 42,757
  • 9
  • 93
  • 110
karthikeyan
  • 3,821
  • 3
  • 22
  • 45
0

Try this:

        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss zzz"];
        NSTimeZone *currentTimeZone = [NSTimeZone localTimeZone];
        [dateFormatter setTimeZone:currentTimeZone];

        NSString *time = [dateFormatter stringFromDate:[NSDate date]];

        NSLog(@"TIME IS %@", time);

For more details, about NSDateFormatter, read this:

http://realmacsoftware.com/blog/working-with-date-and-time

Mrunal
  • 13,982
  • 6
  • 52
  • 96