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);
Get Today's Date:NSDate* date = [NSDate date];
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).
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.
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.
All you have to do is:
NSLog(@"Todays date is %@",[formatter stringFromDate:todaysDate]);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With