简体   繁体   中英

setting time when formatting date using NSDateformatter

I have following code to convert string to date. Is it possible that it sets time as "00:00:00" and not the current time?

NSDateFormatter *dateformat = [[NSDateFormatter alloc] init];
[dateformat setDateFormat:@"yyyy-MM-dd"];
NSString *str = @"2014-08-08";
NSDate *dt = [dateformat dateFromString:str];

This gives dt as "2014-08-08 15:20:00 +0000" because I did the operation at 15:20.

Edit: I am using this date to convert it to integer later to store it in database:

int t = [dt timeIntervalSince1970];

If you are displaying the date dt with NSLog you will see what the date description method provides. If you want to see the date in a specific way that suits you use NSDateFormatter to format the date.

Example:

NSDateFormatter *dateformat = [[NSDateFormatter alloc] init];
[dateformat setDateFormat:@"yyyy-MM-dd"];
NSString *str = @"2014-08-08";
NSDate *dt = [dateformat dateFromString:str];

NSDateFormatter *displayDateformat = [[NSDateFormatter alloc] init];
[displayDateformat setDateFormat:@"yyyy-MM-dd"];
NSString *displayDateString = [displayDateformat stringFromDate:dt];
NSLog(@"displayDateString: %@", displayDateString);

Output:

2014-08-08

Note per Apple docs: "This method returns a time value relative to an absolute reference date—the first instant of 1 January 2001, GMT."

A good practice is to use NSDateComponents

NSDate *yourDate = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:yourDate];
[calendar setTimeZone:[NSTimeZone localTimeZone]];
// Set the time components manually
[dateComponents setHour:0];
[dateComponents setMinute:0];
[dateComponents setSecond:0];            

yourDate = [calendar dateFromComponents:dateComponents];

Update

iOS8 :

[[NSCalendar currentCalendar] startOfDayForDate:[NSDate date]];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM