Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I NSLog an NSDate?

With the code pasted below, I am trying to log an NSDate. What am I doing wrong here?

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"YYYY-MM-dd"];
NSDate *todaysDate;
todaysDate = [NSDate date];
NSLog(@"Todays date is %@",formatter);
like image 597
Steven Schafer Avatar asked Aug 29 '13 21:08

Steven Schafer


People also ask

How do I get today's date in Objective C?

Get Today's Date:NSDate* date = [NSDate date];

What is NSDate?

NSDate objects encapsulate a single point in time, independent of any particular calendrical system or time zone. Date objects are immutable, representing an invariant time interval relative to an absolute reference date (00:00:00 UTC on 1 January 2001).

How do I print the time in Objective C?

NSDate *date = [NSDate date]; to get the current date and time. Use NSDateFormatter to format it. See this link for a how-to on date and time formatting.

Is NSDateFormatter thread safe?

Thread Safety On earlier versions of the operating system, or when using the legacy formatter behavior or running in 32-bit in macOS, NSDateFormatter is not thread safe, and you therefore must not mutate a date formatter simultaneously from multiple threads.


2 Answers

All you have to do is:

  NSLog(@"Todays date is %@",[formatter stringFromDate:todaysDate]);
like image 122
Abdullah Shafique Avatar answered Oct 13 '22 13:10

Abdullah Shafique


What you are doing wrong is you haven't done anything to associate the date with the formatter. So, you would want to do something like this:

NSLog(@"Todays date is %@", [formatter stringFromDate:todaysDate];

The NSDate doesn't know anything about formatting (just date information), and the NSDateFormatter doesnt really know anything about dates, just how to format them. So you have to use methods like -stringFromDate: to actually format the date for pretty human-readable display.

If what you need is to just see the date information and don't need a particular format, you don't need a formatter to log a date:

NSLog(@"Todays date is %@", todaysDate);

Will work fine to give you the -description of the NSDate object. I wouldn't use this for anything you display to the user (do use an NSDateFormatter for that), but this is handy if you're just debugging and need to see information about an NSDate object.

like image 40
hsoi Avatar answered Oct 13 '22 13:10

hsoi