starwar2012
starwar2012
采纳率79.3%
2013-03-15 07:21 阅读 2.1k
已采纳

特定日期时NSDate是空值

在获取特定时期时得到空字符。

比如13/03/2013
代码:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MM/dd/yyyy HH:mm:ss a"];
NSDate *myDate = [formatter dateFromString:@"12/03/2013 5:47:00 AM"];
NSDate *myDate1 = [formatter dateFromString:@"13/03/2013 6:25:48 AM"];           

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
[df setDateFormat:@"yyyy-MM-dd HH:mm"];
NSString *datestr = [df stringFromDate:myDate];
NSString *datestr1 = [df stringFromDate:myDate1];
NSLog(@"date object %@,%@",datestr,datestr1);
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

3条回答 默认 最新

  • 已采纳
    redCoral_ redCoral_ 2013-03-15 07:33

    需要看一下标准日期格式:

      NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"dd/MM/yyyy hh:mm:ss a"];
        NSDate *myDate = [formatter dateFromString:@"12/03/2013 5:47:00 AM"];
        NSDate *myDate1 = [formatter dateFromString:@"13/03/2013 6:25:48 AM"];  
    
        [formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
        NSString *datestr = [formatter stringFromDate:myDate];
        NSString *datestr1 = [formatter stringFromDate:myDate1];
        NSLog(@"date object %@,%@",datestr,datestr1);
    
    点赞 评论 复制链接分享
  • zhanglei5415 ReyZhang 2013-03-17 08:34

    第一步:解析
    解析目前的格式

    NSString *curStr=@"13/03/2013";
    NSDateFormater *formater=[[NSDateFormater alloc] init];
    [formater setDateFormat:@"dd/MM/yyyy"];
    NSDate *getDate=[formater dateFromString:curStr];
    NSLog(@"get date is: %@",getDate);
    

    第二步:格式化
    格式化成你想要的格式。如:2013-03-13

    [formater setDateFormat:@"yyyy-MM-dd"];
    NSString *getStr=[formater stringFromDate:getDate];
    NSLog(@"finally result: %@",getStr);
    
    点赞 评论 复制链接分享
  • xiaoyaokk xiaoyaokk 2013-03-26 02:58
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
        [formatter setDateFormat:@"dd/MM/yyyy hh:mm:ss a"];
        NSDate *myDate = [formatter dateFromString:@"12/03/2013 5:47:00 AM"];
        NSDate *myDate1 = [formatter dateFromString:@"13/03/2013 6:25:48 AM"];  
    
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
        NSString *datestr = [formatter stringFromDate:myDate];
        NSString *datestr1 = [formatter stringFromDate:myDate1];
        NSLog(@"date object %@,%@",datestr,datestr1);
    
    点赞 评论 复制链接分享

相关推荐