我收到一个包含日期的字符串。我想检查它是否具有“dd/MM/yyyy”格式。现在我正在使用在同一页面中找到的代码:
NSDate *date = [dateFormatter dateFromString:dateString];
if(date == nil) {
correctFormat = false;
}
它适用于某些情况,但例如,如果我输入“22-12-1996”而不是“22/12/1996”,它无论如何都会创建日期。还有其他一致的方法吗?
最佳答案
NSDateFormatter处理字符串日期的格式。
Instances of NSDateFormatter create string representations of NSDate objects, and convert textual representations of dates and times into NSDate objects.
试试这个并看看:
// Set date format according to your string date format
// e.g.: For,
// 22-12-1996 -> @"dd-MM-yyyy"
// 22/12/1996 -> @"dd/MM/yyyy"
// 1996-12-22 03:45:20 -> @"yyyy-MM-dd HH:mm:ss"
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"dd/MM/yyyy";
//dateFormatter.dateFormat = @"dd-MM-yyyy";
NSDate *date = [dateFormatter dateFromString:dateString];
if(date == nil) {
correctFormat = false;
}
NSLog("Date: %@",date);
Note: Each pairs of characters in date format relates relevant date component with date instance. You can create any type of date format using date string pattern.
这是 Apple 的文档:Date Formatters
- Date (Day): dd
- Month: MM or MMM or MMMM
- Year: yy or yyyy
以下是日期格式列表:Date Formats
关于ios - 检查 Objective-C 中的日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48421809/