我想以字符串“2012-11-22 10:19:04”中的“20-Sep-2012”格式显示日期。我怎样才能做到这一点?iOS有什么内置方法吗?
问问题
46632 次
5 回答
59
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
于 2012-11-22T05:00:57.323 回答
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);
于 2012-11-22T05:00:41.503 回答
2
Swift 3中 (@Dinesh Raja) 接受的答案:
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)
}
于 2016-10-13T07:45:38.123 回答
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
用这种方法查看我的博客所有信息我的博客链接
于 2012-11-22T05:01:28.400 回答
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
享受编程
于 2012-11-22T05:01:35.467 回答