ios iOS中的当前和更新时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5633896/
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
Current and Updating time in iOS?
提问by h4wkeye
i'm developing a tool for car driving which saves GPS Data, Accelerometer Data and Time for later use.
我正在开发一种用于汽车驾驶的工具,它可以保存 GPS 数据、加速度计数据和时间以供以后使用。
Acceleration is the least Priority, though.
不过,加速是最不重要的。
All i need is a little code example so i can get the current system time printed as an updating clock in Xcode because i want it to save my data as fast and as often as possible :>
我只需要一个小代码示例,这样我就可以将当前系统时间打印为 Xcode 中的更新时钟,因为我希望它尽可能快地保存我的数据:>
Thanks in advance for any answers :)
提前感谢您的任何答案:)
h4wkeye
h4wkeye
回答by Jhaliya
To get the current system time use
获取当前系统时间使用
NSDate* currentDate = [NSDate date];
NSDate* currentDate = [NSDate date];
and To get the string representation of NSDate
和获取 NSDate 的字符串表示
- (NSString *)description
Then Use below
然后在下面使用
NSString* dateInString = [currentDate description];
回答by Helmut Taylor
Like to share this simple code example. Just put this any where in your myClass code. You May find more formatting examples > Format String for the iPhone NSDateFormatter.
喜欢分享这个简单的代码示例。只需将其放在 myClass 代码中的任何位置即可。您可能会找到更多格式示例 > iPhone NSDateFormatter 的格式字符串。
// Get current date time
NSDate *currentDateTime = [NSDate date];
// Instantiate a NSDateFormatter
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// Set the dateFormatter format
//[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
// or this format to show day of the week Sat,11-12-2011 23:27:09
[dateFormatter setDateFormat:@"EEE,MM-dd-yyyy HH:mm:ss"];
// Get the date time in NSString
NSString *dateInStringFormated = [dateFormatter stringFromDate:currentDateTime];
NSLog(@"%@", dateInStringFormated);
// Release the dateFormatter
[dateFormatter release];
回答by ashokdy
Use this code in viewDidLoad or viewWillAppear
在viewDidLoad中或viewWillAppear中使用此代码。
-(void)callUpdate
{
NSTimer *timer = [[NSTimer alloc]initWithFireDate:[NSDate date] interval:0.1 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES];
}
-(void)updateTimer
{
NSDateFormatter *dateformatter=[[NSDateFormatter alloc]init];
[dateformatter setDateFormat:@"MM-dd-yyyy HH:mm:ss"];
NSString *dateInStringFormated=[dateformatter stringFromDate:[NSDate date]];
label.text = dateInStringFormated;
}
or else just alloc the timer in the viewDidLoad or viewWillAppear and when you need to stop the timer use
或者只是在 viewDidLoad 或 viewWillAppear 中分配计时器以及何时需要停止计时器使用
[timer invalidate];