Iphone NSDate - get today's date and make time

We hope it will be fast for someone! I'm struggling to figure out why the code below does not work. I am trying to get the date today (ex: 2010-09-10) and manually add the time. It seems he always returns 00:00:00. any ideas I'm wrong in?

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
dateFormatter.dateFormat = @"yyyy-MM-dd";

NSString *actualDate = [dateFormatter stringFromDate:[NSDate date]];
NSDate *sDate = [dateFormatter dateFromString:[NSString stringWithFormat:@"%@ %@", actualDate, @"01:00:00"]];
NSDate *eDate = [dateFormatter dateFromString:[NSString stringWithFormat:@"%@ %@", actualDate, @"23:59:59"]];

NSDate objects return the format 2010-09-10 00:00:00 + 01: 00 all the time. Somewhere it’s just not gaining time ... any ideas? many thanks.

* UPDATE *

Below is the code. I did this on a suggestion and gained access to the elements and updated them.

unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSDate *date = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comps = [calendar components:unitFlags fromDate:date];

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
dateFormatter.dateFormat = @"yyyy-MM-dd hh:mm:ss";

//update for the start date
[comps setHour:0];
[comps setMinute:0];
[comps setSecond:0];
NSDate *sDate = [calendar dateFromComponents:comps];

//update for the end date
[comps setHour:23];
[comps setMinute:59];
[comps setSecond:59];
NSDate *eDate = [calendar dateFromComponents:comps];
+3
source share
2 answers

NSCalendar. . , , NSDate .

( : . ( NSDateFormatter, ), .)

+3

, , NSDate . , , :

NSDate *                date;
NSString *              string, *timestamp;
NSDateFormatter *       formatter;

timestamp = @"17:30";

formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat: @"yyyy-MM-dd "];
[formatter setTimeZone: [NSTimeZone localTimeZone]];

string = [formatter stringFromDate: [NSDate date]];
string = [string stringByAppendingString: timestamp];

[formatter setDateFormat: @"yyyy-MM-dd HH:mm"];
date = [formatter dateFromString: string];
+1

Source: https://habr.com/ru/post/1764239/


All Articles