UTC world standard time, calculated by atomic clocks, the time standard we use today. UTC stands for time zone 0.
GMT Greenwich Mean Time (GMT), a uniform measure by the British Observatory Greenwich Mean Time, is used to distinguish time zones.
Time and timestamp
Get the time by initializing NSDate to get the time object that we need, converted to a string representation
Gets the difference between a timestamp from a time object to the UNIX (January 1, 1970 00:00:00 UTC) time, converted to a string representation
Current time and UTC time
UTC indicates that the time zone 0 is the unified time standard. The current time is the time zone modified by GMT
NSDate
Initialize the
NSDate *date = [NSDate new]; NSDate *date = [NSDate date]; NSDate *date = [NSDate date]; / / UTC, NSDate * date = 0 time zone [NSDate dateWithTimeIntervalSinceNow: 0]; / / than standard UTC to increase or decrease seconds NSDate * date = [NSDate dateWithTimeIntervalSince1970:0]; / / from UTC1970-01-01 00:00:00 began to increase or reduce the number of seconds NSDate * date = [NSDate dateWithTimeIntervalSinceReferenceDate: 1); / / UTC from 2001-01-01 00:00:00 l began to increase or reduce the number of seconds NSDate * date = [NSDate dateWithTimeInterval: interval sinceDate: date]. // Increase or decrease the number of seconds from the specified dateCopy the code
Time to time stamp
- (NSString *)getTimestamp:(NSString *)time {
NSDateFormatter *format = [NSDateFormatter new];
format.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSDate *date = [format dateFromString:time];
NSInteger timeInterval = [date timeIntervalSince1970];
NSString *timestamp = [NSString stringWithFormat:@"%ld",(long)timeInterval];
return timestamp;
}Copy the code
Time stamp transfer time
- (NSString *)getTime:(NSString *)timestamp {
NSDateFormatter *format = [NSDateFormatter new];
format.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSTimeInterval timeInterval = [timestamp integerValue];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSString *time = [format stringFromDate:date];
return time;
}Copy the code
NSDate Time to NSString time
The first is that the string does not contain the GMT timeZone abbreviation. The timeZone is defined as GMT0 timeZone - (void)timeString {NSDate *date = [NSDate date]; NSDateFormatter *format = [NSDateFormatter new]; // Custom time standard format.dateFormat = @"yyy-MM-dd HH:mm:ss";
format.timeZone = [NSTimeZone timeZoneWithName:@"GMT"];
NSString *datestr = [format stringFromDate:date];
}Copy the code
Second: string containing GMT time zone abbreviation, dateFormat defines @"yyy-MM-dd HH:mm:ss Z"GMT +0000 - (void)timeString {NSDate *date = [NSDate date]; NSTimeZone *zone = [NSTimeZone systemTimeZone]; NSDateFormatter *format = [NSDateFormatter new]; // Custom time standard format.dateFormat = @"yyy-MM-dd HH:mm:ss Z"; NSUInteger interval = [zone secondsFromGMTForDate:date]; / / the current time zone and the number of seconds to UTC time zone difference NSDate * currentdate = [date dateByAddingTimeInterval: interval]; NSString *datestr = [format stringFromDate:date]; }Copy the code
The second method is not recommended. Despite the difficulty of changing the GMT in the string from yyyY-MM-dd HH: MM :ss Z to +0000, the amount of code is increased, and the NSDate after the successful conversion is the current time in the time zone 0. An error occurs when we use its value to calculate other time zones.
The first method is recommended. Try not to fetch GMT when fetching NSDate, which has less code and reduces unnecessary NSDate calculation. Directly using NSDate to NSString is more accurate
NSString Time to NSDate
NSDate = time zone 0 UTC - (void)timedate {NSDate *date = [NSDate date]; NSDateFormatter *format = [NSDateFormatter new]; // Custom time standard format.dateFormat = @"yyy-MM-dd HH:mm:ss";
NSDate *daStr = [format dateFromString:@"The 2019-07-06 21:21:05"];
}Copy the code
Time comparison and calculation
Compare for equality
BOOL bl = [date isEqualToDate:date];Copy the code
Comparison of morning and evening
NSDate *earlier = [date earlierDate:daStr]; NSDate *later = [date laterDate:daStr]; NSDate *later = [date laterDate:daStr]; // Compare the two times and get the next timeCopy the code
NSDateFormatter
The dateFormat commonly used
@"yyy-MM-dd HH:mm:ss Z"/ / @ GMT format"yyyy-MM-dd"
@"HH:mm:ss"
@"yyyy-MM-dd HH:mm:ss"//hh indicates @ for 12 hours"yyyy-MM-dd HH:mm:ss:sss"// Accurate to 13 bits per millisecondCopy the code
timeZone NSTimeZone
-
Name: indicates the time zone name
-
SecondsFromGMT: indicates the difference in seconds between the current time zone and UTC
-
Abbreviation: Abbreviation for GMT
/ / time zone names, abbreviations to define the time zone [NSTimeZone timeZoneWithName: zone. The abbreviation]; / / time to define the time zone [NSTimeZone timeZoneForSecondsFromGMT: zone. SecondsFromGMT];Copy the code
timeStyle
When/min (12 hours format) NSDateFormatterShortStyle; 12 hours/minutes/seconds (format) NSDateFormatterMediumStyle; Hour/minute/second (12 hours GMT format) NSDateFormatterLongStyle;Copy the code
NSDateComponents
NSDateComponents controls the date and time through the NSCalendar calendar object
Initialize the
NSDate *date = [NSDate date]; NSCalendar *calendar = [NSCalendar currentCalendar]; NSDateComponents *comp = [Calendar Components: NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond | NSCalendarUnitTimeZone | NSCalendarUnitWeekday fromDate:date]; // com.year year // com.month month // com.day day // com.hour hour // com.minute Minute // com.second second // com.timezone Time zone information (name/abbreviation/secondsFromGMT)Copy the code
For weeks
NSCalendarUnitWeekday for years, under the condition of the current week NSCalendarUnitWeekOfYear unit belongs to which weeks NSCalendarUnitWeekOfMonth units for the month conditions, belong to the first weekCopy the code
Gets the exact calendar unit
- (void)getDayUnit { NSDate *date = [NSDate date]; NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]; / / the calendar type NSRange range = [calendar rangeOfUnit: NSCalendarUnitDayinUnit:NSCalendarUnitYear forDate:date]; // The absolute time range of a smaller calendar unit within a larger calendar unit}Copy the code
Calendar type NSCalendarIdentifierChinese said in the Chinese calendar, NSCalendarIdentifierGregorian said the Gregorian calendar
Get the absolute date calculated after the calendar unit is added to the given date by the given date component
- (void)getNewComp { NSDate * date = [NSDate date]; NSDateComponents * comp = [[NSDateComponents alloc] init]; comp.year = -1; // Properties are unsigned, with - for previous calendar units and + for future calendar units com.day = 1; comp.hour = 2; NSCalendar * calendar = [NSCalendar currentCalendar]; //comp: component, date: date, NSCalendarMatchStrictly: Forward or backward (date) NSDate * newData = [calendar dateByAddingComponents: comp toDate: date options: NSCalendarMatchStrictly]; NSDateFormatter * formatter = [NSDateFormatter new]; formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSString * time = [formatter stringFromDate:newData];
}Copy the code
NSDateComponents The date component goes to NSDate time
NSDateComponents * comp = [[NSDateComponents alloc] init]; comp.year = 2019; // If the component is not set, it defaults to the default value com.month = 7; comp.day = 9; comp.hour = 13; comp.minute = 14; NSCalendar * calendar = [NSCalendar currentCalendar]; NSDate * date = [calendar dateFromComponents:comp]; NSDateFormatter * formatter = [NSDateFormatter new]; formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSString * str = [formatter stringFromDate:date];Copy the code
The last
Technical summary:
1. We often encounter timestamp conversions. Whether it is time or timestamp, it is important to know what the two are.
2. In the conversion, we often see the time zone difference between UTC and actual time. Here, the time zone is combined to understand the whole calculation method.
3. Format can be regarded as a controllable treasure box, providing you with a variety of convenient operation services; Calendar is a steward to help NSDateComponents complete the control of the date; Components, on the other hand, have many Components that allow you to freely use rich extensions to the date functionality.
4. In addition to the initialization of NSDate time is very important, most of the above are [NSDate date] initialization method, when you see the whole article combined with their own understanding, you can also pass in a certain time to write the above function to encapsulate flexible use.