IOS gets the exchange instance of current time and timestamp

Time:2020-8-28

In the project development, it is inevitable to encounter the use of current time, such as network request upload message, appointment, calendar and other functions.

1. Get year, month, day, hour, minute, second

Implementation code:


NSDate *date1 = [NSDate date];
NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
[formatter1 setDateStyle:NSDateFormatterMediumStyle];
[formatter1 setTimeStyle:NSDateFormatterShortStyle];
[formatter1 setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
NSString *DateTime1 = [formatter1 stringFromDate:date1];

STR is the time we need. The time style in the code (“yyyy MM DD HH: mm: SS”) can be modified according to our needs, such as:

20170901112253 ==> (“YYYYMMddHHmmss”)

If you only want to get the date, the code is as follows:


NSDate *date1 = [NSDate date];
NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
[formatter1 setDateStyle:NSDateFormatterMediumStyle];
[formatter1 setTimeStyle:NSDateFormatterShortStyle];
[formatter1 setDateFormat:@"YYYY-MM"];
NSString *DateTime1 = [formatter1 stringFromDate:date1];

2. Distinguish whether the system time is 24 hours or 12 hours

The code is as follows:

//The acquisition system is 24-hour or 12-hour
NSString *formatStringForHours = [NSDateFormatter dateFormatFromTemplate:@"j" options:0 locale:[NSLocale currentLocale]];
NSRange contains = [formatStringForHours rangeOfString:@"a"];
BOOL thisAMPM = contains.location != NSNotFound;

Thisampm = = true is a 12-hour system, otherwise it is a 24-hour system

3. String to timestamp

The code is as follows:

//Time stamp to string conversion
//Datenow is the current time
NSString *timeSp = [NSString stringWithFormat:@"%d", (long)[datenow timeIntervalSince1970]]; 
//The value of the timestamp
NSLog(@"timeSp:%@",timeSp);

4. Time stamp to string

The code is as follows:

//Timestamp to string
NSString *timeStr = "1506064573";
NSTimeInterval interval=[timeStr doubleValue] / 1000.0;
NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
//Instantiate an nsdateformatter object
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
//Set the time format, here you can set the format you need
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *currentDateStr = [dateFormatter stringFromDate:date];

The above example of IOS getting the current time and time stamp is the whole content shared by Xiaobian. I hope it can give you a reference, and I hope you can support developeppaer more.