objective-c 获取当前系统时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2313263/
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 22:59:15  来源:igfitidea点击:

Get current system time?

objective-ciphonecocoa-touch

提问by fuzzygoat

Whats the best way to get the current time (HH:MM:SS) using Objective-C. I would guess I should be looking at NSDate & NSDateFormatter. I had a quick glance at the docs and it looked a little more convoluted than I expected, so I thought I would check here to make sure I was on the right track.

使用 Objective-C 获取当前时间 (HH:MM:SS) 的最佳方法是什么。我想我应该看看 NSDate 和 NSDateFormatter。我快速浏览了文档,它看起来比我预期的要复杂一些,所以我想我会在这里检查以确保我在正确的轨道上。

gary

加里

回答by Ben Zotto

NSDate * now = [NSDate date];
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateFormat:@"HH:mm:ss"];
NSString *newDateString = [outputFormatter stringFromDate:now];
NSLog(@"newDateString %@", newDateString);
[outputFormatter release];

回答by Aaron

You are, in fact, on the right track. Use

事实上,你是在正确的轨道上。用

NSDate *date = [NSDate date];

to get the current date and time. Use NSDateFormatterto format it. See this linkfor a how-to on date and time formatting.

获取当前日期和时间。使用NSDateFormatter格式化。有关日期和时间格式的操作方法,请参阅此链接

For your situation, you could do this:

对于您的情况,您可以这样做:

NSDate *date = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"%H:%M:%S"];
NSString *timeString = [formatter stringFromDate:date];

回答by user3119237

NSDateFormatter *DateFormatter=[[NSDateFormatter alloc] init];

[DateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];  
NSLog(@"%@",[DateFormatter stringFromDate:[NSDate date]]);