iPhone OS:如何为特定日期创建 NSDate?

发布于 2024-08-27 22:06:24 字数 52 浏览 11 评论 0原文

看起来很简单,但我似乎找不到方法来做到这一点。

很高兴看到几种不同的方法。

Seems like a simple thing but I can't seem to find a way to do it.

It would be great to see a couple different methods.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

岁月静好 2024-09-03 22:06:24

@Chuck 的答案是正确的,并引导我找到以下代码。我想我会分享:

NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:10];
[comps setMonth:10];
[comps setYear:2010];
NSDate *date = [[NSCalendar currentCalendar] dateFromComponents:comps];

@Chuck's answer is correct, and lead me to the following code. Thought I'd share:

NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:10];
[comps setMonth:10];
[comps setYear:2010];
NSDate *date = [[NSCalendar currentCalendar] dateFromComponents:comps];
把时间冻结 2024-09-03 22:06:24

您可以使用这个

NSString *dateString = @"03-Sep-11";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"dd-MMM-yy";
NSDate *date = [dateFormatter dateFromString:dateString];

希望这会对您有所帮助。

You can use this

NSString *dateString = @"03-Sep-11";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"dd-MMM-yy";
NSDate *date = [dateFormatter dateFromString:dateString];

Hope this will help you out.

可遇━不可求 2024-09-03 22:06:24

如果您正在谈论特定的日历日期而不是 UNIXy 日期,您可能需要 NSCalendar 的 dateFromComponents:

If you're talking about a specific calendar date rather than a UNIXy date, you probably want NSCalendar's dateFromComponents:.

另类 2024-09-03 22:06:24

Swift 示例

示例通常是最简单的学习方法。这里有几个例子。

现在

这是最简单的。

let currentDateTime = Date()

2017 年 2 月 20 日

// Specify date components
var dateComponents = DateComponents()
dateComponents.year = 2017
dateComponents.month = 2
dateComponents.day = 20

// Create date from components
let userCalendar = Calendar.current // user calendar
let dateThisPostWasUpdated = userCalendar.date(from: dateComponents)

1976 年 4 月 1 日

// Specify date components
var dateComponents = DateComponents()
dateComponents.year = 1976
dateComponents.month = 4
dateComponents.day = 1

// Create date from components
let userCalendar = Calendar.current // user calendar
let appleFoundedDate = userCalendar.date(from: dateComponents)

需要更多详细信息...?

还有其他创建日期的方法。如果您想了解这些以及如何显示日期,那么查看我更完整的答案。

Swift Examples

Examples are often the easiest way to learn. Here are a few examples.

Now

This one is the easiest.

let currentDateTime = Date()

February 20, 2017

// Specify date components
var dateComponents = DateComponents()
dateComponents.year = 2017
dateComponents.month = 2
dateComponents.day = 20

// Create date from components
let userCalendar = Calendar.current // user calendar
let dateThisPostWasUpdated = userCalendar.date(from: dateComponents)

April 1, 1976

// Specify date components
var dateComponents = DateComponents()
dateComponents.year = 1976
dateComponents.month = 4
dateComponents.day = 1

// Create date from components
let userCalendar = Calendar.current // user calendar
let appleFoundedDate = userCalendar.date(from: dateComponents)

Need more details...?

There are other ways to create dates, too. If you want to learn those, as well as how to display a date, then see my fuller answer.

一曲爱恨情仇 2024-09-03 22:06:24

See the documentation for NSDate. You can use the dateFromString: method of NSDateFormatter or the dateFromComponents: method of NSCalendar.

悲喜皆因你 2024-09-03 22:06:24

我在寻找这个问题的答案时发现了这个帖子,但后来我在我的 Big Nerd Ranch Objective-C 编程书中找到了一个很好的例子。归功于他们,而不是我。

  NSDateComponents *myBDay  =[[NSDateComponents alloc] init];
    [myBDay setDay:22];
    [myBDay setMonth: 04];
    [myBDay setYear: 1984];
    [myBDay setHour:9];
    [myBDay setMinute:25];
    [myBDay setSecond:35];

    NSCalendar *g = [[ NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate *dateOfBirth = [g dateFromComponents:myBDay];

I found this thread while looking for an answer to this question but then I found a good example in one my Big Nerd Ranch Objective-C Programming book. Credit to them, not me.

  NSDateComponents *myBDay  =[[NSDateComponents alloc] init];
    [myBDay setDay:22];
    [myBDay setMonth: 04];
    [myBDay setYear: 1984];
    [myBDay setHour:9];
    [myBDay setMinute:25];
    [myBDay setSecond:35];

    NSCalendar *g = [[ NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate *dateOfBirth = [g dateFromComponents:myBDay];
深白境迁sunset 2024-09-03 22:06:24

这很荒谬,不是吗?

2013 年中,Apple 仍然没有提供设置 NSDate 值的简单方法。

在我当前的 iPad 项目中,我不敢相信我必须暂时停止工作来编写自己的帮助程序类以从 NSDate 获取 Year 值。我的意思是,来吧,这是基本的东西。

无论如何,这是我在项目中使用的帮助程序类,用于将字符串转换为 NSDate 值:

@implementation DateHelper

+(NSDate*)parseDateString:(NSString *)dateString
{
    NSDateFormatter *rfc3339TimestampFormatterWithTimeZone = [[NSDateFormatter alloc] init];
    [rfc3339TimestampFormatterWithTimeZone setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
    [rfc3339TimestampFormatterWithTimeZone setDateFormat:@"MMM dd, yyyy"];

    NSDate *theDate = nil;
    NSError *error = nil;
    if (![rfc3339TimestampFormatterWithTimeZone getObjectValue:&theDate forString:dateString range:nil error:&error]) {
        NSLog(@"Date '%@' could not be parsed: %@", dateString, error);
    }

    return theDate;
}

@end

使用此代码,您可以使用以下内容设置 NSDate 值:

NSDate* date = [DateHelper parseDateString:@"Jul 16, 2013"];

注意:此函数基于从此处获取的代码:
https://stackoverflow.com/a/3968411/391605

我的解决方案已经使用下面的代码,但我发现有时,它只是无法解析,并且会返回nil

//  Take a date string in the format "Oct 23, 2013", and convert it into a NSDate value
//  THIS DOESN'T WORK !  DON'T TRUST THIS CODE !!
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMM dd, yyyy"];
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

NSDate* date = [formatter dateFromString:dateString];

我记得它在“2012 年 10 月 12 日”惨败……这就是为什么我放弃并使用上面显示的更复杂的“parseDateString”函数。

我的观点是……要小心。

一些非常基本的 NSDate 功能无法正常工作......

It is ridiculous, isn't it ?

Mid-2013 and Apple still hasn't provided a simple way to set a NSDate value.

During my current iPad project, I couldn't believe I had to stop productivity for a while to write my own helper class to get the Year value from an NSDate. I mean, come on, this is basic stuff.

Anyway, here's the helper class I used in my project, to convert a string into an NSDate value :

@implementation DateHelper

+(NSDate*)parseDateString:(NSString *)dateString
{
    NSDateFormatter *rfc3339TimestampFormatterWithTimeZone = [[NSDateFormatter alloc] init];
    [rfc3339TimestampFormatterWithTimeZone setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
    [rfc3339TimestampFormatterWithTimeZone setDateFormat:@"MMM dd, yyyy"];

    NSDate *theDate = nil;
    NSError *error = nil;
    if (![rfc3339TimestampFormatterWithTimeZone getObjectValue:&theDate forString:dateString range:nil error:&error]) {
        NSLog(@"Date '%@' could not be parsed: %@", dateString, error);
    }

    return theDate;
}

@end

Using this code, you could set an NSDate value using something like:

NSDate* date = [DateHelper parseDateString:@"Jul 16, 2013"];

Note: this function was based on code taken from here:
https://stackoverflow.com/a/3968411/391605

My solution had been to use the following code, but I found that sometimes, it just wouldn't parse, and would return nil.

//  Take a date string in the format "Oct 23, 2013", and convert it into a NSDate value
//  THIS DOESN'T WORK !  DON'T TRUST THIS CODE !!
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMM dd, yyyy"];
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

NSDate* date = [formatter dateFromString:dateString];

I remember it failed miserably on "Oct 12, 2012"... which is why I gave up and used the more complicated "parseDateString" function shown above.

My point is... be careful.

Some of the very-basic NSDate functions just don't work properly...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文