UIDatepicker 和 NSDate 之间的日期差异

发布于 2025-01-04 23:48:01 字数 6435 浏览 2 评论 0原文

我有一个日期选择器,并将值保存到 .plist 文件,其中包含字符串格式的 UserDate 键。

datepicker 返回的值采用 2013-02-13 11:17:34 +0000 格式。

为了将其保存到 .plist 文件中,我需要将 datepicker 转换为字符串 2013-02-14T19:17:34Z

在其他视图中,我想从 plist 检索 UserDate 并与用户当前日期。我想要不同的日子和时间。

我将 2012-02-12 19:17:34 +0800 转换并传递为 destinationDate 以与 [NSDate new] 进行比较。 我设法计算了两个日期之间的差异。但结果不正确。

如何获得iPhone日期和Datepicker日期之间两个日期的正确差异结果?我需要使用特定时区吗?

额外信息:我住在 GMT+8。我将模拟器日期选择器设置为2012年2月13日,但结果仍然显示倒计时有18小时4分钟。

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
int units = NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;

NSDateComponents *components = [calendar components:units fromDate:[NSDate date] toDate:destinationDate options:0];
[datelabel setText:[NSString stringWithFormat:@"%d%c %d%c %d%c %d%c %d%c", [components month], 'm', [components day], 
                    'd', [components hour], 'h', [components minute], 'm', [components second], 's']];

NSLog

在此处输入图像描述

编辑

Plist 文件。

在此处输入图像描述

保存方法

NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
// get documents path
NSString *documentsPath = [paths objectAtIndex:0];
// get the path to our Data/plist file
NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"Data.plist"];

// set the variables to the values in the text fields
self.userTitle = myTitle.text;
self.userMessage = myMessage.text;  

NSLog(@"METHOD SAVE");

NSLog(@"Datepicker value =  %@", myDate.date );

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSString *mdate = [dateFormatter stringFromDate:myDate.date];
//  [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];

NSLog(@"Converted from date picker, save into plist =  %@", mdate );

self.saveDate = mdate;
//self.userDate = myDate.date;

// create dictionary with values in UITextFields
NSDictionary *plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: userTitle, userMessage, saveDate, nil] forKeys:[NSArray arrayWithObjects: @"Title", @"Message", @"UserDate", nil]]; NSString *error = nil;
// create NSData from dictionary
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];

// check is plistData exists
if(plistData)
{
    // write plistData to our Data.plist file
    [plistData writeToFile:plistPath atomically:YES];
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Success" message:@"Your settings have been saved." delegate:self cancelButtonTitle:nil otherButtonTitles:@"Ok",nil];
    [alert show];
}
else
{
    NSLog(@"Error in saveData: %@", error);
    //[error release];
}

viewWillAppear

- (void)viewWillAppear:(BOOL)animated {
[self.navigationController setNavigationBarHidden:YES];

[super viewWillAppear:animated];

// Data.plist code
// get paths from root direcory
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
// get documents path
NSString *documentsPath = [paths objectAtIndex:0];
// get the path to our Data/plist file
NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"Data.plist"];

// check to see if Data.plist exists in documents
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath])
{
    // if not in documents, get property list from main bundle
    plistPath = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"plist"];
}

// read property list into memory as an NSData object
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
NSString *errorDesc = nil;
NSPropertyListFormat format;
// convert static property liost into dictionary object
NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization propertyListFromData:plistXML mutabilityOption:NSPropertyListMutableContainersAndLeaves format:&format errorDescription:&errorDesc];
if (!temp)
{
    NSLog(@"Error reading plist: %@, format: %d", errorDesc, format);
}

NSLog(@"Plist Title: %@", [temp objectForKey:@"Title"]);
NSLog(@"Plist Message: %@", [temp objectForKey:@"Message"]);
NSLog(@"Plist date: %@", [temp objectForKey:@"UserDate"]);

userTitle.text = [NSString localizedStringWithFormat:@"%@", [temp objectForKey:@"Title"]];
userMessage.text = [NSString localizedStringWithFormat:@"%@", [temp objectForKey:@"Message"]];

//http://stackoverflow.com/questions/1070354/how-do-i-get-the-current-date-in-cocoa

NSDate* now = [[NSDate alloc] initWithTimeIntervalSinceNow:3600];
userCoundown.text = [NSString stringWithFormat:@"%@",now];  

NSString *uDate = [[NSString alloc] init];
uDate = [temp objectForKey:@"UserDate"];
NSLog(@"Plist date in string - %@", uDate);

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSDate *ddate = [dateFormatter dateFromString:uDate];
[dateFormatter setDateFormat:@"yyyy-MM-dd H:mm:ss Z"];

NSLog(@"Format date from Plist -  %@", [dateFormatter stringFromDate:ddate]);

//NSLog(@"GMT format from Plist - %@", timeStamp);

//http://www.epochconverter.com/#
destinationDate = ddate;
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateLabel) userInfo:nil repeats:YES];
}

updatelabel

-(void)updateLabel {

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
int units = NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;

NSDateComponents *components = [calendar components:units fromDate:[NSDate date] toDate:destinationDate options:0];
[datelabel setText:[NSString stringWithFormat:@"%d%c %d%c %d%c %d%c %d%c", [components month], 'm', [components day], 
                    'd', [components hour], 'h', [components minute], 'm', [components second], 's']];
}

I have a datepicker and I save the value to .plist file with key UserDate in string format.

The value returns from datepicker is in 2013-02-13 11:17:34 +0000 format.

In order to save it into to .plist file I need to convert datepicker to string 2013-02-14T19:17:34Z

In other View, I want to retrieve back the UserDate from plist and compare with the user current date. I want days and hours different.

I convert and pass 2012-02-12 19:17:34 +0800 as destinationDate to compare with [NSDate new].
I managed to calculate the difference between two date. But the result is not correct.

How to get the correct difference result for two dates between iPhone's date and Datepicker's date? Do I need to use a specific timezone?

Extra info: I live in GMT+8. I set the simulator datepicker to Feb 13 2012, yet the result still say the countdown has 18hours and 4 minutes.

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
int units = NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;

NSDateComponents *components = [calendar components:units fromDate:[NSDate date] toDate:destinationDate options:0];
[datelabel setText:[NSString stringWithFormat:@"%d%c %d%c %d%c %d%c %d%c", [components month], 'm', [components day], 
                    'd', [components hour], 'h', [components minute], 'm', [components second], 's']];

NSLog

enter image description here

Edit

Plist file.

enter image description here

save method

NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
// get documents path
NSString *documentsPath = [paths objectAtIndex:0];
// get the path to our Data/plist file
NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"Data.plist"];

// set the variables to the values in the text fields
self.userTitle = myTitle.text;
self.userMessage = myMessage.text;  

NSLog(@"METHOD SAVE");

NSLog(@"Datepicker value =  %@", myDate.date );

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSString *mdate = [dateFormatter stringFromDate:myDate.date];
//  [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];

NSLog(@"Converted from date picker, save into plist =  %@", mdate );

self.saveDate = mdate;
//self.userDate = myDate.date;

// create dictionary with values in UITextFields
NSDictionary *plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: userTitle, userMessage, saveDate, nil] forKeys:[NSArray arrayWithObjects: @"Title", @"Message", @"UserDate", nil]]; NSString *error = nil;
// create NSData from dictionary
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];

// check is plistData exists
if(plistData)
{
    // write plistData to our Data.plist file
    [plistData writeToFile:plistPath atomically:YES];
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Success" message:@"Your settings have been saved." delegate:self cancelButtonTitle:nil otherButtonTitles:@"Ok",nil];
    [alert show];
}
else
{
    NSLog(@"Error in saveData: %@", error);
    //[error release];
}

viewWillAppear

- (void)viewWillAppear:(BOOL)animated {
[self.navigationController setNavigationBarHidden:YES];

[super viewWillAppear:animated];

// Data.plist code
// get paths from root direcory
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
// get documents path
NSString *documentsPath = [paths objectAtIndex:0];
// get the path to our Data/plist file
NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"Data.plist"];

// check to see if Data.plist exists in documents
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath])
{
    // if not in documents, get property list from main bundle
    plistPath = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"plist"];
}

// read property list into memory as an NSData object
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
NSString *errorDesc = nil;
NSPropertyListFormat format;
// convert static property liost into dictionary object
NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization propertyListFromData:plistXML mutabilityOption:NSPropertyListMutableContainersAndLeaves format:&format errorDescription:&errorDesc];
if (!temp)
{
    NSLog(@"Error reading plist: %@, format: %d", errorDesc, format);
}

NSLog(@"Plist Title: %@", [temp objectForKey:@"Title"]);
NSLog(@"Plist Message: %@", [temp objectForKey:@"Message"]);
NSLog(@"Plist date: %@", [temp objectForKey:@"UserDate"]);

userTitle.text = [NSString localizedStringWithFormat:@"%@", [temp objectForKey:@"Title"]];
userMessage.text = [NSString localizedStringWithFormat:@"%@", [temp objectForKey:@"Message"]];

//http://stackoverflow.com/questions/1070354/how-do-i-get-the-current-date-in-cocoa

NSDate* now = [[NSDate alloc] initWithTimeIntervalSinceNow:3600];
userCoundown.text = [NSString stringWithFormat:@"%@",now];  

NSString *uDate = [[NSString alloc] init];
uDate = [temp objectForKey:@"UserDate"];
NSLog(@"Plist date in string - %@", uDate);

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSDate *ddate = [dateFormatter dateFromString:uDate];
[dateFormatter setDateFormat:@"yyyy-MM-dd H:mm:ss Z"];

NSLog(@"Format date from Plist -  %@", [dateFormatter stringFromDate:ddate]);

//NSLog(@"GMT format from Plist - %@", timeStamp);

//http://www.epochconverter.com/#
destinationDate = ddate;
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateLabel) userInfo:nil repeats:YES];
}

updatelabel

-(void)updateLabel {

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
int units = NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;

NSDateComponents *components = [calendar components:units fromDate:[NSDate date] toDate:destinationDate options:0];
[datelabel setText:[NSString stringWithFormat:@"%d%c %d%c %d%c %d%c %d%c", [components month], 'm', [components day], 
                    'd', [components hour], 'h', [components minute], 'm', [components second], 's']];
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

丑丑阿 2025-01-11 23:48:01

NSDate 保持 GMT 时间。如果您有时区,则必须指定它们。

问题不清楚,所以这不是一个完整的答案,但应该为 plist 中的 NSDate 提供一些帮助。

以下是使用 NSDate 创建、写入和读取 plist 的示例:

NSDictionary *plistDict = [NSDictionary dictionaryWithObjectsAndKeys:
                           userTitle,   @"Title",
                           userMessage, @"Message",
                           saveDate,    @"UserDate",
                           nil];

[plistDict writeToFile:filePath atomically:YES];

NSDictionary *plistDictRead = [NSDictionary dictionaryWithContentsOfFile:filePath];
NSDate *dateRead = [plistDictRead objectForKey:@"UserDate"];

无需将 NSDate 转换为字符串,也无需使用 NSPropertyListSerialization

NSDate keeps time in GMT. If you have time zones you will have to specify them.

The question is not clear so this is not a complete answer but should provide some help with NSDate in a plist.

Here is an example of creating, writing and reading a plist with a NSDate:

NSDictionary *plistDict = [NSDictionary dictionaryWithObjectsAndKeys:
                           userTitle,   @"Title",
                           userMessage, @"Message",
                           saveDate,    @"UserDate",
                           nil];

[plistDict writeToFile:filePath atomically:YES];

NSDictionary *plistDictRead = [NSDictionary dictionaryWithContentsOfFile:filePath];
NSDate *dateRead = [plistDictRead objectForKey:@"UserDate"];

There is no need to convert the NSDate to a string and no need to use NSPropertyListSerialization.

游魂 2025-01-11 23:48:01

请记住创建 NSDate,然后使用有效的时区和日历输出它!

查看我在另一篇文章中回答的类似问题:
UIDatePicker 返回错误的 NSDate

Remember to create the NSDate and then output it with a valid timezone and calendar!

Check a similar question I answered in another post:
UIDatePicker return wrong NSDate

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文