ios 为 NSDateFormatter 设置日期格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5739598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
setting date format for NSDateFormatter
提问by Joey
I am trying to set the date format for something like "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_Patternsfor guidelines on how to specify it and I think my issue is in the format itself.
我正在尝试为“2011-04-21 03:31:37.310396”之类的内容设置日期格式。我想我没有得到正确的小数秒。我正在查看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?
帮助?
回答by suprandr
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
我猜你可能忘了点
回答by malhal
As per Zaph's comment in the other answer: the maximum number of S is 3. Any more just produce zeros.
根据 Zaph 在另一个答案中的评论:S 的最大数量为 3。任何更多只会产生零。
E.g.
例如
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