如何创建一个 NSDate 日期对象? [英] How to create an NSDate date object?

查看:59
本文介绍了如何创建一个 NSDate 日期对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从日、月和年创建 NSDate?似乎没有任何方法可以做到这一点,他们已经删除了类方法 dateWithString(他们为什么要这样做?!).

How can I create an NSDate from the day, month and year? There don't seem to be any methods to do this and they have removed the class method dateWithString (why would they do that?!).

推荐答案

您可以为此编写一个类别.我这样做了,这就是代码的样子:

You could write a category for this. I did that, this is how the code looks:

//  NSDateCategory.h

#import <Foundation/Foundation.h>

@interface NSDate (MBDateCat) 

+ (NSDate *)dateWithYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day;

@end



//  NSDateCategory.m

#import "NSDateCategory.h"

@implementation NSDate (MBDateCat)

+ (NSDate *)dateWithYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day {
    NSCalendar *calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
    NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
    [components setYear:year];
    [components setMonth:month];
    [components setDay:day];
    return [calendar dateFromComponents:components];
}

@end

像这样使用它:NSDate *aDate = [NSDate dateWithYear:2010 month:5 day:12];

这篇关于如何创建一个 NSDate 日期对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆