is there any easy way to get Date?

253 views Asked by At

I'm new to iPhone development. I want to set default date to NSDate Object as string. I don't see any easy way or method...

I think there might be a method in NSCalender? If there's such a method, please tell me.

Thanks in advance.

5

There are 5 answers

1
David On

Edit: Added time to format string.

You will need to look at the NSDate and NSDateFormatter classes. Here's a simple example of how to use them:

NSString* defaultDateString = [NSString stringWithFormat:@"2011-01-22 15:30:00"];
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate* defaultDate = [dateFormatter dateFromString:defaultDateString];
[dateFormatter release];

and if you wanted to get the string from a date you can just use:

NSString* defaultDateString = [dateFormatter stringFromDate:defaultDate];
0
xyzzycoder On

I'm not totally clear on what you are asking, but to create an instance of an NSDate object with the current date, one calls: NSDate * myDate = [NSDate date];

If you are saying that you have a c-string or NSString that needs to be parsed to initialize an NSDate object, that's another question.

I have some code posted here: How get a datetime column in SQLite with Objective C

that shows how to create NSDates from NSStrings using NSDateFormatter.

3
Ankit On
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc]init]autorelease];
[dateFormatter setDateFormat:@"yyyy-mm-dd"];
NSDate *yourDate = [dateFormatter dateFromString:@"2011-01-26"];
2
Jason Coco On

If you want to create an NSDate from a string, you need to use an NSDateFormatter to do it. It's important to note that the formatter will use the current locale's time zone when constructing the date, unless you put a time-zone in as part of the format. For more information about constructing time zones, see NSTimeZone.

For example, to create a date using the ubiquitous format '2011-01-16 00:00' in UTC, you would do:

NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
// Only certain abbreviations are okay, like UTC. See docs for more info
[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];

NSDate* midnight_26_jan_2011_utc = [formatter dateFromString:@"2011-01-26 00:00"];

// this will display in your system locale
// (for me, it shows 2011-01-25 19:00 +0500 because I'm America/New_York time)
NSLog(@"date: %@", midnight_26_jan_2011_utc);
[formatter release];
0
Sharon Aju On
NSDateFormatter *DateFormatter=[[NSDateFormatter alloc] init];
[DateFormatter setTimeZone:[NSTimeZone defaultTimeZone]];
[DateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"]; //here,you can set the date format as you need

NSDate *now = [[[NSDate alloc] init]autorelease];
NSString *theDate = [DateFormatter stringFromDate:now];

Now, you can use the string the date. :)