处理日期时间NSDate

 

获取当前日期时间的代码如下:

    NSDate *dateToDay = [NSDate date];
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-DD HH:mm:ss"];
    NSLocale *local = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    [df setLocale:local];
    NSString *myDataString = @"2009-09-15 18:30:00";

从字符串生成日期对象的代码如下:

NSDate *myData = [df dateFromString:myDataString];

日期比较的代码如下:

    switch ([dateToDay compare:myData]) {
        case NSOrderedSame:
            NSLog(@"These dates are the same!");
            break;
            
        case NSOrderedAscending:
            NSLog(@"dateToDay is earlier than myDate!");
            break;
            
        case NSOrderedDescending:
            NSLog(@"mydate is earlier than dateToDay");
            break;
            
        default:
            NSLog(@"Bad times. Invalid enum value returned.");
            break;
    }

注意:掌握NSDate和NSString相互之间的转换。

完整代码如下:

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{
    
    NSDate *dateToDay = [NSDate date];
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-DD HH:mm:ss"];
    NSLocale *local = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    [df setLocale:local];
    NSString *myDataString = @"2009-09-15 18:30:00";
    
    NSDate *myData = [df dateFromString:myDataString];
    
    switch ([dateToDay compare:myData]) {
        case NSOrderedSame:
            NSLog(@"These dates are the same!");
            break;
            
        case NSOrderedAscending:
            NSLog(@"dateToDay is earlier than myDate!");
            break;
            
        case NSOrderedDescending:
            NSLog(@"mydate is earlier than dateToDay");
            break;
            
        default:
            NSLog(@"Bad times. Invalid enum value returned.");
            break;
    }
    return 0;
}

 

 

NSData转换为NSString的代码如下:

    NSMutableData *data;
    NSString *tmpdata = [[NSString alloc] initWithString:data encoding:NSASCIIStringEncoding];
    NSLog(@"[***] DATA:%@" , tmpdata);
    [tmpdata release];

NSString转换为NSData的代码如下:

    NSString *str = @"teststring";
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];

 

posted on 2013-12-15 10:25  猿人谷  阅读(2263)  评论(0编辑  收藏  举报