我从API
收到字符串格式的以下日期2015-04-18 06:08:28.000000
我希望日期格式为d/M/yyyy
我尝试了以下
NSString *datevalue = (NSString*)value;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"d/M/yyyy"];
NSDate *date = [formatter dateFromString:datevalue];
NSString *currentDate = [formatter stringFromDate:date];
这会返回NIL,可能是什么问题,或者我如何在objective-c中格式化这些日期?
感谢。
答案 0 :(得分:1)
您不能使用相同的格式化程序来读取和写入日期字符串,因为它们是不同的。输入日期的格式不正确。
// input string date: 2015-04-18 06:08:28.000000
// [formatter setDateFormat:@"d/M/yyyy"]; // incorrect
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSSSSS"];
以下是示例代码
//
// main.m
// so29732496
//
// Created on 4/19/15.
//
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSLog(@"Hello, World!");
NSString *dateStringFromAPI = @"2015-04-18 06:08:28.000000";
NSString * const kAPIDateFormat = @"yyyy-MM-dd HH:mm:ss.SSSSSS";
// convert API date string
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:kAPIDateFormat];
NSDate *apiDate = [formatter dateFromString:dateStringFromAPI];
// now if I was output the api date to another format
// I have to change the formatter
[formatter setDateFormat:@"dd/M/yyyy"];
NSString *currentDate = [formatter stringFromDate:apiDate];
NSLog(@"Current Date: %@", currentDate);
}
return 0;
}
答案 1 :(得分:1)
只想添加Black Frog的答案:正如他所说,你需要不同的格式化程序来进行阅读/写作。
但正确的格式应为:
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSSSSS"];
根据苹果文档,小数秒应该用'S'格式化。
见这里: NSDateFormat
此处还有一个完成任务的示例:
NSString *datevalue = @"2015-04-18 06:08:28.000000";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSSSSS"];
NSDate *date = [formatter dateFromString:datevalue];
[formatter setDateFormat:@"dd/MM/yyyy"];
NSString *currentDate = [formatter stringFromDate:date];
NSLog(@"%@",date);
NSLog(@"%@",currentDate);
答案 2 :(得分:1)
您应该将yyyy-MM-dd HH:mm:ss.SSSSSSS
格式字符串用于将API日期转换为NSDate
对象的日期格式化程序,正如其他人所讨论的那样。但是,您还需要考虑此格式化程序的timeZone
和locale
属性。
通常RFC 3339日期在GMT中交换。使用您的API确认,但通常是GMT / UTC / Zulu。如果是这样,您可能还需要明确设置时区:
formatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
但请确认API预期的时区。
一个更微妙的问题是使用非Gregorian日历处理用户
formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
有关详细信息,请参阅Apple Technical Q&A 1480。
显然,这些dateFormat
,timeZone
和locale
属性仅用于将API日期字符串转换为NSDate
对象。然后在输出最终用户的日期时,您将使用单独的格式化程序,默认为标准timeZone
和locale
属性,并使用您想要输出的任何dateFormat
字符串。 (坦率地说,我通常不建议将dateFormat
字符串用于用户输出格式化程序,而只是使用dateStyle
和timeStyle
属性的相应值。)