DatePicker is not returning the correct date. Is i

2019-09-20 06:16发布

问题:

I saved a task's due date as 8:45 today. However the log shows the due date as

2013-04-26 01:45:46 +0000

What gives? Here's my code

#import "DatePickerViewController.h"
#import <Parse/Parse.h>
#import "ListItemObject.h"

@class ListItemObject;

@interface DatePickerViewController ()


@end

@implementation DatePickerViewController

@synthesize dateLabel;
@synthesize pick;
@synthesize listFieldText;



- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    pick.timeZone = [NSTimeZone localTimeZone];

    UIBarButtonItem *saveDate = [[UIBarButtonItem alloc]
                                 initWithTitle:@"Save Date"
                                 style:UIBarButtonItemStyleDone
                                 target:self
                                 action:@selector(saveList:)];
    self.navigationItem.rightBarButtonItem = saveDate;
    [pick addTarget:self action:@selector(updateDateLabel:) forControlEvents:UIControlEventValueChanged];
}

-(IBAction)saveList:(id)sender {
    NSLog(@"%@", pick.date);
    [ListItemObject saveListItem:[PFUser currentUser] withName:listFieldText withDate:pick.date];

    [self.navigationController popViewControllerAnimated:YES];
    [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
}


-(IBAction)updateDateLabel:(id)sender {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterLongStyle];
    [formatter setTimeStyle:NSDateFormatterMediumStyle];
    dateLabel.text = [formatter stringFromDate:pick.date];

}

Do I need to do something similar as what I did with NSDateFormatter?

回答1:

The date and time displayed represents the same time as the time you saved, but in GMT. This is because an NSDate represents a single point in time, with no information on formatting or adjusting that time for various time zones. Logging the NSDate returned by pick.date will display the time in generic GMT.

Using an NSDateFormatter, as you did in updateDateLabel():

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterLongStyle];
[formatter setTimeStyle:NSDateFormatterMediumStyle];
dateLabel.text = [formatter stringFromDate:pick.date];

will provide you with the time adjusted for your local time zone, which should then match 8:45.



回答2:

The +0000 means you're seeing the date in the UTC time zone. NSLog(@"%@", someDate) will just return the description property from an NSDate. If you want the value to be adjusted to a particular time zone, you will need to set the timeZone property of an NSDateFormatter.