0

Is it possible to print an NSDate object via NSLog without also printing the hour, minute, seconds? What I want it to log is this format yyyy-MM-dd, without the hour, minute, seconds.

I already have an NSDateFormatter with yyyy-MM-dd but when I print the NSDate object via NSLog, it still gives me the hour, minute, second.

Is there a way to do this without creating another string from the date object then logging that string?

Jano
  • 62,815
  • 21
  • 164
  • 192
aresz
  • 2,589
  • 6
  • 34
  • 51
  • 1
    You can use an NSDateFormatter to produce any format you want. The point is, you must format the date into a string, not simply wave the formatter around an NSDate and expect to change the NSDate. – Hot Licks Oct 30 '13 at 23:03
  • Thanks for the comment. I have already formatted my NSDate via NSDateFormatter with the yyyy-MM-dd format. But when I NSLog the NSDate object, it still gives me the hours, minutes, seconds – aresz Oct 30 '13 at 23:06
  • 2
    `NSDateFormatter` doesn't modify an existing `NSDate` object, nor does it produce a new one. It just offers you the ability to produce an `NSString` of a desired format, from an `NSDate`. So yes, you'll have to format it every time you want to print it to the console, or retain the `NSString` if the date is not changing. – Craig Otis Oct 30 '13 at 23:11

2 Answers2

1

When NSLog encounters an objective-c object (via the %@ token), it calls the method -[NSObject description] and prints the resulting string in its place. NSDate's implementation of that method prints out hours, minutes, and seconds. The only way to have it print something differently is to generate a string yourself using NSDateFormatter.

ianyh
  • 619
  • 5
  • 8
  • I see. That makes sense. So there isn't really any other way to do this without creating my own string. – aresz Oct 30 '13 at 23:11
1

You can subclass nsdate and override the description method to return a formatted string. Or write a category to do the same and just call the category method in your log statements.

pickwick
  • 3,134
  • 22
  • 30
  • 1
    Yeah, a category would be the way to go, if one wants to do anything at all in this regard. – Hot Licks Oct 31 '13 at 00:31
  • It's worth noting that overriding methods using categories is not recommended. See http://stackoverflow.com/questions/5272451/overriding-methods-using-categories-in-objective-c – ianyh Nov 01 '13 at 16:22
  • I didn't mean to imply that: only to add another method that does what he wants – pickwick Nov 02 '13 at 17:37