[英]setting date format for NSDateFormatter
I am trying to set the date format for something like "2011-04-21 03:31:37.310396". 我正在尝试设置类似“2011-04-21 03:31:37.310396”的日期格式。 I think I'm not getting the fractional seconds right.
我想我没有得到正确的小数秒。 I'm looking at http://unicode.org/reports/tr35/tr35-10.html#Date_Format_Patterns for guidelines on how to specify it and I think my issue is in the format itself.
我正在查看http://unicode.org/reports/tr35/tr35-10.html#Date_Format_Patterns以获取有关如何指定它的指导原则,我认为我的问题在于格式本身。
NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ssSSSSSS";
NSDate* serverDate = [dateFormatter dateFromString:stringFormOfDate];
Help? 救命?
try 尝试
NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss.SSSSSS";
NSDate* serverDate = [dateFormatter dateFromString:@"2011-04-21 03:31:37.310396"];
NSLog(@"%@", serverDate);
I guess you probably forgot the dot 我想你可能忘记了这个点
As per Zaph's comment in the other answer: the maximum number of S is 3. Any more just produce zeros. 根据Zaph在另一个答案中的评论:S的最大数量为3.再做一次只产生零。
Eg 例如
dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss.SSSSSS"; // Last 3 'S' ignored.
Then @"2011-04-21 03:31:37.311396" will produce 2011-04-21 03:31:37.311000
To maintain full microsecond precision try this magic: 要保持完整的微秒级精度,请尝试以下方法:
-(NSDate *)_dateFromUtcString:(NSString *)utcString{
if(!utcString){
return nil;
}
static NSDateFormatter *df = nil;
if (df == nil) {
df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
[df setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
}
NSArray* parts = [utcString componentsSeparatedByString:@"."];
NSDate *utcDate = [df dateFromString:parts[0]];
if(parts.count > 1){
double microseconds = [parts[1] doubleValue];
utcDate = [utcDate dateByAddingTimeInterval:microseconds / 1000000];
}
return utcDate;
}
Now an NSString "2011-04-21 03:31:37.310396" will parse fully to an NSDate 2011-04-21 03:31:37.310396 现在一个NSString“2011-04-21 03:31:37.310396”将完全解析为NSDate 2011-04-21 03:31:37.310396
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.