如何在ios中将字符串转换为日期以进行警报通知?

时间:2021-07-29 16:04:15

My Question is, I have a string something like that 07:25AM Now my question is how can i make this string to date for location notification for an alarm app.

我的问题是,我有一个类似于07:25 AM的字符串现在我的问题是如何使这个字符串到目前为警报应用程序的位置通知。

So far i have done like this:

到目前为止,我这样做了:

   NSDateFormatter * dateFormatter = [[NSDateFormatter alloc]init];
   [dateFormatter setDateFormat:@"HH:mm a"];
   NSDate * timeNotFormatted = [dateFormatter dateFromString:@"07:25 AM"];

But it's showing this time: 1999-12-31 18:25:00 +0000 and i want something like this todays date 7:25:00

但它显示这个时间:1999-12-31 18:25:00 +0000我想要今天这样的日期7:25:00

I am little bit new at date conversion so if someone help me then it will helpful for me.

我在日期转换方面有点新意,所以如果有人帮助我,那么这对我有帮助。

Regards

Emon

1 个解决方案

#1


You'd have to use NSDateComponents. It's a bit verbose, but it would look a little like this:

你必须使用NSDateComponents。它有点冗长,但看​​起来有点像这样:

NSDateFormatter *formatter = [NSDateFormatter new];
formatter.dateFormat = @"hh:mm a";

NSDate *timestamp = [formatter dateFromString:@"07:25 AM"];

NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDateComponents *timestampComponents = [calendar components:NSCalendarUnitHour|NSCalendarUnitMinute fromDate:timestamp];
NSDateComponents *currentTimeComponents = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:[NSDate new]];
currentTimeComponents.hour = timestampComponents.hour;
currentTimeComponents.minute = timestampComponents.minute;

NSDate *result = [calendar dateFromComponents:currentTimeComponents];

#1


You'd have to use NSDateComponents. It's a bit verbose, but it would look a little like this:

你必须使用NSDateComponents。它有点冗长,但看​​起来有点像这样:

NSDateFormatter *formatter = [NSDateFormatter new];
formatter.dateFormat = @"hh:mm a";

NSDate *timestamp = [formatter dateFromString:@"07:25 AM"];

NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDateComponents *timestampComponents = [calendar components:NSCalendarUnitHour|NSCalendarUnitMinute fromDate:timestamp];
NSDateComponents *currentTimeComponents = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:[NSDate new]];
currentTimeComponents.hour = timestampComponents.hour;
currentTimeComponents.minute = timestampComponents.minute;

NSDate *result = [calendar dateFromComponents:currentTimeComponents];