Mutual conversion of time and timestamp in iOS, ios time Conversion
// Obtain the timestamp of the current system time
# Pragma mark-get the timestamp of the current time
+ (NSInteger) getNowTimestamp {
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[Formatter setDateStyle: NSDateFormatterMediumStyle];
[Formatter setTimeStyle: nsdateformatter1_style];
[Formatter setDateFormat: @ "YYYY-MM-dd HH: mm: ss"]; // ---------- set the format you want. The difference between hh and HH is 12-hour, respectively, 24-hour system
// Set the time zone, which is sometimes important for Time Processing
NSTimeZone * timeZone = [NSTimeZone timeZoneWithName: @ "Asia/Beijing"];
[Formatter setTimeZone: timeZone];
NSDate * datenow = [NSDate date]; // current time
NSLog (@ "Current Device time: % @", [formatter stringFromDate: datenow]);
// Time to timestamp method:
NSInteger timeSp = [[NSNumber numberWithDouble: [datenow timeIntervalSince1970] integerValue];
NSLog (@ "Current Device timestamp: % ld", (long) timeSp); // The timestamp Value
Return timeSp;
}
// Convert a time to a timestamp
# Pragma mark-converts a time to a timestamp
+ (NSInteger) timeSwitchTimestamp :( NSString *) formatTime andFormatter :( NSString *) format {
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[Formatter setDateStyle: NSDateFormatterMediumStyle];
[Formatter setTimeStyle: nsdateformatter1_style];
[Formatter setDateFormat: format]; // (@ "YYYY-MM-dd hh: mm: ss") ---------- set the format you want. The difference between hh and HH is as follows: 12-hour and 24-hour respectively
NSTimeZone * timeZone = [NSTimeZone timeZoneWithName: @ "Asia/Beijing"];
[Formatter setTimeZone: timeZone];
NSDate * date = [formatter dateFromString: formatTime]; // ------------ convert the string to nsdate by formatter
// Time to timestamp method:
NSInteger timeSp = [[NSNumber numberWithDouble: [date timeIntervalSince1970] integerValue];
NSLog (@ "convert a time to timestamp & timeSp: % ld", (long) timeSp); // The timestamp Value
Return timeSp;
}
// Convert a timestamp into a time
# Pragma mark-converts a timestamp into a time
+ (NSString *) timestampSwitchTime :( NSInteger) timestamp andFormatter :( NSString *) format {
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[Formatter setDateStyle: NSDateFormatterMediumStyle];
[Formatter setTimeStyle: nsdateformatter1_style];
[Formatter setDateFormat: format]; // (@ "YYYY-MM-dd hh: mm: ss") ---------- set the format you want. The difference between hh and HH is as follows: 12-hour and 24-hour respectively
NSTimeZone * timeZone = [NSTimeZone timeZoneWithName: @ "Asia/Beijing"];
[Formatter setTimeZone: timeZone];
NSDate * confromTimesp = [NSDate dateWithTimeIntervalSince1970: timestamp];
NSLog (@ "1296035591 = % @", confromTimesp );
NSString * confromTimespStr = [formatter stringFromDate: confromTimesp];
// NSLog (@ "& confromTimespStr =: % @", confromTimespStr );
Return confromTimespStr;
}