【问题标题】:How can I display a specific text related to a specific date using date picker?如何使用日期选择器显示与特定日期相关的特定文本?
【发布时间】:2013-08-13 14:58:56
【问题描述】:

我是 iOS 新手,并不熟悉它的所有 API。我发现了如何在文本字段中显示选定的日期,但我不知道要写什么来显示与特定日期相关的特定(选定)文本。

这是我用来显示日期的代码。您知道我需要更改哪些内容才能在特定日期编写自己的文本吗?:

 #import "ViewController.h"

 @implementation ViewController
 @synthesize datePicker;
 @synthesize dateLabel;

 - (void)didReceiveMemoryWarning
 {
     [super didReceiveMemoryWarning];
     // Release any cached data, images, etc that aren't in use.
 }

 #pragma mark - View lifecycle

 - (void)viewDidLoad
 {
     [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
 }

 - (void)viewDidUnload
 {
     [self setDateLabel:nil];
     [self setDatePicker:nil];
     [super viewDidUnload];
     // Release any retained subviews of the main view.
     // e.g. self.myOutlet = nil;
 }

 - (void)viewWillAppear:(BOOL)animated
 {
     [super viewWillAppear:animated];
 }

 - (void)viewDidAppear:(BOOL)animated
 {
     [super viewDidAppear:animated];
 }

 - (void)viewWillDisappear:(BOOL)animated
 {
    [super viewWillDisappear:animated];
 }

 - (void)viewDidDisappear:(BOOL)animated
 {
    [super viewDidDisappear:animated];
 }

 - (BOOL)shouldAutorotateToInterfaceOrientation (UIInterfaceOrientation)interfaceOrientation
 {
     // Return YES for supported orientations
     return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
 }

 - (IBAction)touchButton:(id)sender {

     NSDate *dateSelect = [datePicker date];
     NSString *dateStamp = [[NSString alloc]initWithFormat:@"The date is %@", dateSelect];

     dateLabel.text = dateStamp;
 }
 @end

(我有一个按钮、日期选择器和一个文本字段)

非常感谢您的回答。

【问题讨论】:

  • 你绑定并设置了日期选择器的代理?
  • 您的问题真的是关于如何格式化日期值的输出吗?
  • 不,如果我的问题不清楚,我很抱歉。我希望一年中的每一天都有一个文本,例如每日报价。

标签: ios datepicker


【解决方案1】:

您必须使用格式化程序。看看……

...
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH:mm"]; <--- This will show hours and minutes
NSString *dateStamp = [formatter stringFromDate:date];
...

在 setDateFormat 中,您可以通过这种方式设置所需的输出格式...

dd - 天 MM - 月 yyyy - 年 HH - 小时 毫米 - 分钟 ss - 秒

...所以 [formatter setDateFormat:@"MM/dd/yyyy, HH:mm"] 会得到类似 "01/01/2013, 13:45" 的信息。

【讨论】:

  • 硬编码日期格式不是一个好主意。最好设置日期格式化程序的dateStyle。这样,日期或时间的格式将根据用户的区域设置正确。
  • @rmaddy 是的,这不是屏幕显示的最佳方式,但非常适合精确格式的日期(例如:发送到不接受时间戳的服务器的日期)。他要求“能够在特定日期写我自己的文本”。
  • 发布的代码显示了标签中显示的日期。标签显示给用户。因此,它们应该根据用户的区域设置正确格式化,而不是特定的格式。这是对 OP 的建议,而不是对您的建议。
猜你喜欢
  • 1970-01-01
  • 2021-06-17
  • 2021-07-29
  • 1970-01-01
  • 2012-12-20
  • 2016-11-26
  • 2019-03-22
  • 1970-01-01
  • 2015-05-01
相关资源
最近更新 更多