ios - 检查 NSString 的特定日期格式

标签 ios cocoa-touch nsstring nsdate

我有一个 NSString,我需要检查它是否采用这种特定格式 MM/DD/YY。然后我需要将其转换为 NSDate。对此的任何帮助将不胜感激。旁注 - 我四处搜索,人们建议使用 RegEx,我从来没有使用过这个,而且一般不清楚。谁能给我指出一个好的资源/解释。

最佳答案

NSString *strDate1 = @"02/09/13";
NSString *strDate2 = @"0123/234/234";

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd/MM/yy"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
NSDate *dateFormat1 = [dateFormatter dateFromString:strDate1];
NSDate *dateFormat2 = [dateFormatter dateFromString:strDate2];

NSLog(@"%@", dateFormat1); // prints 2013-09-02 00:00:00 +0000
NSLog(@"%@", dateFormat2); // prints (null)

因此,如果 NSDate 为 nil,您将知道何时格式不正确。如果您需要更多信息,这里是文档的链接:https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW1

关于ios - 检查 NSString 的特定日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18602602/

相关文章:

objective-c - 检查两个 NSString 是否相似

ios - 如何根据 objective-c 中的内存地址知道对象名称

ios - UIImageView 意外改变大小

android - iOS 上的 CSS 与 Android 上的不同吗?

ios - 也将 cocoapods 添加到测试目标?

cocoa - 在 Swift 中使用核心数据实现枚举的最佳方式

iphone - 从 iPhone 上的 sleep 事件中唤醒?

iphone - 具有 clearColor 背景的 UITableView 部分?

UILabel + UIButton iOS 本地化最佳实践

ios - 由于UITextView中的自定义行间距,导致文本选择无法正确进行