iOS Method for Getting Current Time and Current Timestamp
- 2021-09-20 21:40:49
- OfStack
// Get the current time
+(NSString*)getCurrentTimes{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// ---------- Set the format you want ,hh And HH Difference between : Representation separately 12 Hourly system ,24 Hourly system
[formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
// Now time , You can output it to see what format it is
NSDate *datenow = [NSDate date];
//---------- Will nsdate Press formatter Format to nsstring
NSString *currentTimeString = [formatter stringFromDate:datenow];
NSLog(@"currentTimeString = %@",currentTimeString);
return currentTimeString;
}
There are two ways to get the current timestamp (in seconds)
+(NSString *)getNowTimeTimestamp{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // ---------- Set the format you want ,hh And HH Difference between : Representation separately 12 Hourly system ,24 Hourly system
// Setting Time Zone , This is sometimes very important for the processing of time
NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
[formatter setTimeZone:timeZone];
NSDate *datenow = [NSDate date];// Now time , You can output it to see what format it is
NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
return timeSp;
}
+(NSString *)getNowTimeTimestamp2{
NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
NSTimeInterval a=[dat timeIntervalSince1970];
NSString*timeString = [NSString stringWithFormat:@"%0.f", a];// Convert to character type
;
return timeString;
}
// Get the current timestamp (In milliseconds)
+(NSString *)getNowTimeTimestamp3{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss SSS"]; // ---------- Set the format you want ,hh And HH Difference between : Representation separately 12 Hourly system ,24 Hourly system
// Setting Time Zone , This is sometimes very important for the processing of time
NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
[formatter setTimeZone:timeZone];
NSDate *datenow = [NSDate date];// Now time , You can output it to see what format it is
NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]*1000];
return timeSp;
}