How to get the date with specific hour and minute of today from "HH:mm" string in Objecive-C

39 views Asked by At

I have a time string like "HH:mm" format and I want to get a NSDate object of today at that time.

I am using NSDateFormatter but it not work.

Here is my code:

NSString *dateString = @"21:00";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm"];
NSDate *date = [dateFormatter dateFromString:dateString];
// date:    __NSTaggedDate *    2000-01-01 07:00:00 UTC 0xfa629653dac0e51b

I want the date to be 2022-10-27 21:00:00;

1

There are 1 answers

0
Adrian B On BEST ANSWER

The defaultDate property on NSDateFormatter does what you want :

NSString *dateString = @"21:00";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm"];
dateFormatter.defaultDate = [NSDate date];
NSDate *date = [dateFormatter dateFromString:dateString];
// 2022-10-27 20:00:26 UTC