objective-c 在目标c中以自定义格式获取字符串中的当前时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1684904/
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
Getting Current Time in string in Custom format in objective c
提问by Sagar R. Kothari
I want current time in following format in a string.
我想要字符串中的以下格式的当前时间。
dd-mm-yyyy HH:MM
dd-mm-yyyy HH:MM
How?
如何?
回答by Carl Norum
You want a date formatter. Here's an example:
你想要一个日期格式化程序。下面是一个例子:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd-MM-yyyy HH:mm"];
NSDate *currentDate = [NSDate date];
NSString *dateString = [formatter stringFromDate:currentDate];
回答by Stephen Canon
Either use NSDateFormatteras Carl said, or just use good old strftime, which is also perfectly valid Objective-C:
要么NSDateFormatter像 Carl 所说的那样使用,要么就使用 good old strftime,这也是完全有效的 Objective-C:
#import <time.h>
time_t currentTime = time(NULL);
struct tm timeStruct;
localtime_r(¤tTime, &timeStruct);
char buffer[20];
strftime(buffer, 20, "%d-%m-%Y %H:%M", &timeStruct);
回答by Zorayr
Here is a simple solution:
这是一个简单的解决方案:
- (NSString *)stringWithDate:(NSDate *)date
{
return [NSDateFormatter localizedStringFromDate:date
dateStyle:NSDateFormatterMediumStyle
timeStyle:NSDateFormatterNoStyle];
}
Change the dateStyleand timeStyleto match your formatting requirement.
更改dateStyle和timeStyle以符合您的格式要求。
回答by AmirHossein
Maybe this will be more readable :
也许这会更具可读性:
NSDateFormatter *date = [[NSDateFormatter alloc] init];
[date setDateFormat:@"HH:mm"];
NSString *dateString = [date stringFromDate:[NSDate date]];
[self.time setText:dateString];
First of all we create an NSDateFormatterbuilt-in in obj-c with the name date, then we apply it by [[NSDateFormatter alloc] init];. After that we say to the code procesor that we want our date to have HOUR/MINUTE/SECOND. Finally we should make our date to be an string to work with alert or set value of a label , to do this we should create an string with NSString method then we use this : [date stringFromDate:[NSDate date]]
首先,我们在 obj-c 中创建了一个名为date 的内置NSDateFormatter,然后我们通过[[NSDateFormatter alloc] init]应用它;. 之后,我们对代码处理器说我们希望我们的日期有 HOUR/MINUTE/SECOND。最后,我们应该让我们的日期成为一个字符串来处理警报或设置标签值,为此我们应该使用 NSString 方法创建一个字符串然后我们使用这个:[date stringFromDate:[NSDate date]]
Have Fun with It .
玩得开心。

