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

Time:10-28

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;

CodePudding user response:

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
  • Related