以字符串格式存储时间HH:MM:来自json的SS响应。我想将其转换为NSDate以进行本地通知。 试着 NSString * datestr = @" 21:00:00&#34 ;;
NSDateFormatter *dateformat = [[NSDateFormatter alloc]init];
[dateformat setDateFormat:@"hh:mm:ss"];
NSDate *date = [dateformat dateFromString:datestr];
NSLog(@"time is %@",date);
获得空闲时间。我有时间格式从json是在21:00:00格式只有没有日期。我想每天为本地通知设置这个时间。
答案 0 :(得分:0)
如果字符串的小时部分范围为0到23,则需要使用HH
。This site has a convenient list of date formatter codes.
然后,您希望将日期转换为NSDateComponents
,以便创建UNCalendarNotificationTrigger
。
@implementation ViewController {
NSDateFormatter *parser;
}
- (void)viewDidLoad {
[super viewDidLoad];
parser = [[NSDateFormatter alloc] init];
parser.dateFormat = @"HH:mm:ss";
parser.calendar = [NSCalendar autoupdatingCurrentCalendar];
}
- (void)createRepeatingNotificationAtTimeOfDay:(NSString *)timeOfDay {
NSDate *date = [parser dateFromString:timeOfDay];
if (date == nil) {
// Couldn't parse the string.
return;
}
NSDateComponents *components = [parser.calendar components:NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond fromDate:date];
if (components == nil) {
// Couldn't extract components.
return;
}
UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:YES];
UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
content.title = @"Daily alarm";
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"dailyalarm" content:content trigger:trigger];
[[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:nil];
}