OGeek|极客世界-中国程序员成长平台

标题: ios - NSDateFormatter 的 NSDate 输出不同 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 22:56
标题: ios - NSDateFormatter 的 NSDate 输出不同

我在使用 NSDate 时遇到了一些问题,实际上我只需要它来验证它是否是有效日期,因为如果它是无效日期,则 date 实例将返回零。但是

NSString *textValue = @"13/12/2014";

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat"MM/dd/yyyy"];

// this should cause the output to have no time
[formatter setTimeStyle:NSDateFormatterNoStyle]; 
formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier"en_US"];
[formatter setCalendar:[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]];
[formatter setTimeZone:[NSTimeZone timeZoneWithName"GMT"]];

NSDate *date = [formatter dateFromString:textValue];

date的结果是2015-01-12 00:00:00 +0000

我期望的结果应该是:nil



Best Answer-推荐答案


NSString *textValue = @"1/12/2014"; 
NSString *textValue1 = @"15/12/2014"; 
NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
[formatter setDateFormat"MM/dd/yyyy"]; 
NSDate *date = [formatter dateFromString:textValue]; 
NSLog(@" >> %@ ",date);
NSDate *date1 = [formatter dateFromString:textValue1]; 
NSLog(@" >> %@ ",date);

关于ios - NSDateFormatter 的 NSDate 输出不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24134322/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4