我想从字符串“2012-11-22 10:19:04”以“20-Sep-2012”格式显示日期。我怎样才能做到这一点?是否有适用于iOS的内置方法?
答案 0 :(得分:58)
NSString *myString = @"2012-11-22 10:19:04";
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSDate *yourDate = [dateFormatter dateFromString:myString];
dateFormatter.dateFormat = @"dd-MMM-yyyy";
NSLog(@"%@",[dateFormatter stringFromDate:yourDate]);
你的日志会像这样打印出来。 22-Nov-2012
答案 1 :(得分:6)
试试这个,
NSString *originalDateString = @"2012-11-22 10:19:04";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];//2012-11-22 10:19:04
然后用它来解析日期字符串,
NSDate *date = [dateFormatter dateFromString:originalDateString];
您可以创建一个新的dateformatter以新格式打印,或者只重复使用现有格式,
[dateFormatter setDateFormat:@"dd-MMM-yyyy"];//22-Nov-2012
NSString *formattedDateString = [dateFormatter stringFromDate:date];
NSLog(@"Date in new format is %@", formattedDateString);
答案 2 :(得分:2)
来自(@Dinesh Raja) Swift 3:
的回答override func viewDidLoad() {
super.viewDidLoad()
print(self.getFormattedDate(myString: "2012-11-22 10:19:04"))
}
func getFormattedDate(myString: String) -> String{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let yourDate = dateFormatter.date(from: myString)!
dateFormatter.dateFormat = "dd-MMM-yyyy"
return dateFormatter.string(from: yourDate)
}
答案 3 :(得分:0)
试试这个
NSString *str = @"2012-11-22 10:19:04";
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [dateFormatter dateFromString: str];
dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"dd-MMM-yyyy"];
NSString *convertedString = [dateFormatter stringFromDate:date];
NSLog(@"Converted String : %@",convertedString);// Print Log (Output) is 22-Nov-2012
查看我的博客
答案 4 :(得分:0)
您可以通过以下方式实现此目的
NSDateFormatter *dfTime = [[NSDateFormatter alloc] init];
[dfTime setDateFormat:@"yyyy--MM-dd HH:mm:ss"];
NSDate *dtTime = [dfTime dateFromString:<Your string>];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"dd-MMM-yyyy"];
<Your result string> = [df stringFromDate:dtTime];
Where <Your string> = @"2012-11-22 10:19:04" &
<Your result string> will be your new string
享受编程