ios - 检查 Objective-C 中的日期格式

标签 ios objective-c date nsdate

我收到一个包含日期的字符串。我想检查它是否具有“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/

相关文章:

python - 如何将整数转换为日期对象python?

ios - Swift:无法将我的值放入标签(可选问题)

ios - 禁用 iPhone X 约束

ios - -[UIView setContentSize :]: unrecognized selector sent to instance 0x16d3be60

ios - 'kCFStreamSSLAllowsExpiredCertificates' 和 'kCFStreamSSLAllowsAnyRoot' 已弃用

php - 使用 PHP 检查指定日期范围内的今天日期

ios - 我们如何以编程方式从 firebase 动态链接短 url 获取深层链接 url?

ios - 无法写入文档目录

iphone - 如何计算用户从当前位置到iPhone中特定位置的当前速度和平均速度?

java - 根据位数分割给出的时间