NSDateFormatterLongStyle 字符串到 NSDate

NSDateFormatterLongStyle string to NSDate

我的 viewController 中有一个默认位置的 UIDataPicker,当我的用户完成选择日期时,我 运行 此代码:

NSString *dateString = [NSDateFormatter localizedStringFromDate:[self.dataPicker date]
                                                          dateStyle:NSDateFormatterLongStyle
                                                  timeStyle:NSDateFormatterNoStyle]; 

使用该代码,我可以按以下格式存储日期:

May 31, 2016

稍后在我的代码中我需要将这个字符串转换成一个真正的日期格式,为此我使用下面的代码:

-(NSDate*)convertStringToDate:(NSString*)date{
    NSString *dateString = date;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    [dateFormatter setDateFormat:@"MM/dd/yyyy"];

    return [dateFormatter dateFromString:dateString];
}

但是这段代码return是一个空值。由于默认设置了日期选择器,我的系统可以接收任何日期格式,但最后我希望将其转换为格式 en_us.

我该如何解决这个问题?

格式化字符串取决于您使用的语言环境。来自 localizedStringFromDate 文档:

Returns string representation of a given date formatted for the current locale using the specified date and time styles.

This method uses a date formatter configured with the current default settings. The returned string is the same as if you configured and used a date formatter as shown in the following example:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.formatterBehavior = NSDateFormatterBehavior10_4;
formatter.dateStyle = dateStyle; formatter.timeStyle = timeStyle;
NSString *result = [formatter stringForObjectValue:date];

意味着,你应该做下一步:

-(NSDate*)convertStringToDate:(NSString*)dateString {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.formatterBehavior = NSDateFormatterBehavior10_4;
    dateFormatter.dateStyle = NSDateFormatterLongStyle;
    dateFormatter.timeStyle = NSDateFormatterNoStyle;
    return [dateFormatter dateFromString:dateString];
}

使用此代码,

-(NSDate*)convertStringToDate:(NSString*)date{
    NSString *dateString = date;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    [dateFormatter setDateFormat:@"MMM d, yyyy"];

    return [dateFormatter dateFromString:dateString];
}

希望对您有所帮助

不要将日期存储为字符串;将其存储为某个参考日期的偏移量(以秒为单位)。

即:

uint64_t offset = (uint64_t)[[self.dataPicker date] timeIntervalSinceReferenceDate];
// store this 64-bit unsigned integer.

这需要更少的 space 并且可以更快地转换 to/from 一个 NSDate 对象。

如果您愿意,可以将偏移量保留为 NSTimeInterval(64 位浮点数 double),但由于您不存储日期和时间,因此 uint64_t 应该做...