简体   繁体   中英

Current and Updating time in iOS?

i'm developing a tool for car driving which saves GPS Data, Accelerometer Data and Time for later use.

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 :>

Thanks in advance for any answers :)

h4wkeye

To get the current system time use

NSDate* currentDate = [NSDate date];

and To get the string representation of NSDate

- (NSString *)description

Then Use below

NSString* dateInString = [currentDate description];

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.

// 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]; 

Use this code in viewDidLoad or 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

[timer invalidate];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM