xcode iPhone:从日期选择器获取日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8936832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 23:02:46  来源:igfitidea点击:

iPhone: Getting date from date picker

iphoneiosxcodenotificationsdatepicker

提问by Henry F

I wrote an app that allows users to enter in a date on a date picker, and the app will alert the user 36 hours before that date arrives. My issue is in the dateFromString:. I'm not sure what to put in there. Here is the code:

我编写了一个应用程序,允许用户在日期选择器上输入日期,该应用程序会在该日期到来前 36 小时提醒用户。我的问题在dateFromString:. 我不确定要在那里放什么。这是代码:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
UILocalNotification *localNotif = [[UILocalNotification alloc] init];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"mm'/'dd'/'yyyy"];
NSDate *eventDate=[dateFormatter dateFromString: ]; 

localNotif.fireDate = [eventDate dateByAddingTimeInterval:-13*60*60];
localNotif.timeZone = [NSTimeZone defaultTimeZone];


localNotif.alertBody = @"Event tommorow!";

localNotif.alertAction = nil;

localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 0;
[[UIApplication sharedApplication]presentLocalNotificationNow:localNotif];    

return YES;

}

}

Any help is much appreciated, thank you!

非常感谢任何帮助,谢谢!

Edit: Here is some additional code that I'm using to save the date they entered on the date picker if that helps:

编辑:这是我用来保存他们在日期选择器上输入的日期的一些附加代码,如果有帮助的话:

- (void)viewDidLoad {
    NSDate *storedDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"DatePickerViewController.selectedDate"];

    [self.datePicker setDate:storedDate animated:NO];
}

And this is the method that saves the data:

这是保存数据的方法:

- (IBAction)dateChanged:(id)sender {

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

NSDate *selectedDate = [self.datePicker date];

[defaults setObject:selectedDate forKey:@"DatePickerViewController.selectedDate"];}

回答by Pavel Oganesyan

Why do you need a string? After making

为什么需要字符串?制作后

[defaults setObject:selectedDate forKey:@"DatePickerViewController.selectedDate"];

[defaults setObject:selectedDate forKey:@"DatePickerViewController.selectedDate"];

you can access your date just like

你可以像访问你的日期一样

NSDate* eventDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"DatePickerViewController.selectedDate"];

Using strings is not so nice with date - you should care about locale and time formats (12 hours or 24 hours) etc.

使用字符串对日期不太好 - 您应该关心语言环境和时间格式(12 小时或 24 小时)等。