如何在不同的标签中获取日期,月份和年份

时间:2016-02-04 13:13:25

标签: ios

我正在使用此代码,并在2个不同的标签中获得日期(完整日期)和时间,但我想要不同标签中的月,日,年和时间:

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.picker addTarget:self action:@selector(datePickerChanged:) forControlEvents:UIControlEventValueChanged];

- (void)datePickerChanged:(UIDatePicker *)datePicker
{
    NSLocale *en_US_POSIX = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
    assert(en_US_POSIX != nil);


    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setLocale:en_US_POSIX];
    [dateFormatter setDateFormat:@"dd-MM-yyyy"];
    NSDate *dateFromString = [[NSDate alloc] init];
    //    dateFromString = [dateFormatter dateFromString:curDate];
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"MMMM d yyyy"];
    NSString *theDate = [dateFormat stringFromDate:dateFromString];
    _lbl.text = theDate;



    NSDate *currentTime = [NSDate date];
    [dateFormatter setDateFormat:@"hh mm"];
     NSString *resultString = [dateFormatter stringFromDate: currentTime];
     _lbl3.text = resultString;

}

提前感谢

1 个答案:

答案 0 :(得分:0)

您需要使用NSDateComponents。这是一个简单的例子

NSDate *dateToCheck = [NSDate date];

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

// Extract date components into components
NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:dateToCheck];

NSString *labelDate     = [NSString stringWithFormat:@"%d", (int)components.day];
NSString *labelMonth    = [NSString stringWithFormat:@"%d", (int)components.month];
NSString *labelYear     = [NSString stringWithFormat:@"%d", (int)components.year];

NSLog(@"%@, %@, %@", labelDate, labelMonth, labelYear);