objective-c NSDate 的字符串描述

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/783395/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 21:26:38  来源:igfitidea点击:

String description of NSDate

objective-ccocoansdate

提问by Ilya Suzdalnitski

I have the following code:

我有以下代码:

[ [NSDate date] descriptionWithLocale: @"yyyy-MM-dd" ]

I want it to return a date in the following format: "2009-04-23"

我希望它以以下格式返回日期:“2009-04-23”

But it returns: Thursday, April 23, 2009 11:27:03 PM GMT+03:00

但它返回:2009 年 4 月 23 日星期四晚上 11:27:03 GMT+03:00

What am I doing wrong?

我究竟做错了什么?

Thank you in advance.

先感谢您。

回答by situee

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
[dateFormatter release];  // delete this line if your project uses ARC
NSLog(@"%@",dateString); 

回答by Sebastian Celis

You are using the wrong method. Instead try descriptionWithCalendarFormat:timeZone:locale:

您使用了错误的方法。而是尝试descriptionWithCalendarFormat:timeZone:locale:

[[NSDate date] descriptionWithCalendarFormat:@"%Y-%m-%d"
                                    timezone:nil
                                      locale:nil];

Also note that the method is expecting a different format than the one in your question. The full documentation for that can be found here.

另请注意,该方法需要与您问题中的格式不同的格式。可以在此处找到完整的文档。

EDIT: Though as Mike noted, you really should be using NSDateFormatter. There are some problems with descriptionWithCalendarFormat:timezone:locale:that Apple mentions in the documentation.

编辑:尽管正如迈克指出的那样,您确实应该使用NSDateFormatter. descriptionWithCalendarFormat:timezone:locale:Apple 在文档中提到的存在一些问题。

回答by Mike Abdullah

Also note that for most cases, NSDateFormatteris to be preferred for its flexibility.

还要注意,在大多数情况下,NSDateFormatter它的灵活性是首选。

There's also a significant performance benefit to be had from re-use of date formatters in many apps.

在许多应用程序中重复使用日期格式化程序还可以获得显着的性能优势。

回答by pix0r

If you don't have NSDate -descriptionWithCalendarFormat:timeZone:locale:available (I don't believe iPhone/Cocoa Touch includes this) you may need to use strftimeand monkey around with some C-style strings. You can get the UNIX timestamp from an NSDate using NSDate -timeIntervalSince1970.

如果你没有NSDate -descriptionWithCalendarFormat:timeZone:locale:可用的(我不相信 iPhone/Cocoa Touch 包括这个),你可能需要使用strftime和猴子来处理一些 C 风格的字符串。您可以使用NSDate -timeIntervalSince1970.