Conversion of iOS time format

Source: Internet
Author: User
Tags month name

When developing iOS programs, it is sometimes necessary to adjust the time format to the format you want, which we can do with the NSDateFormatter class. For example://Instantiate a NSDateFormatter object nsdateformatter *dateformatter = [[NSDateFormatter alloc] init];//set the time format, where you can set the format you want [ Dateformatter setdateformat:@ "Yyyy-mm-dd HH:mm:ss"];//with [NSDate Date] can get system current time nsstring *currentdatestr = [ Dateformatter stringfromdate:[nsdate date]];//output format: 2010-10-27 10:22:13nslog (@ "%@", currentdatestr);// Alloc after the non-use of objects do not forget release[dateformatter release]; The character description (:) time delimiter. In some locales, you can use other characters to represent time separators. The time separator separates hours, minutes, and seconds when formatting time values. The actual character used as the time separator in the formatted output is determined by the current culture value of your application. (/) Date separator. In some locales, you can use other characters to represent the date separator. The date separator separates day, month, and year when formatting date values. The actual character used as the date separator in the formatted output is determined by the current culture of your application. (%) is used to indicate that no matter what letter is trailing, subsequent characters should be read in single-letter format. Also used to indicate that a single-letter format should be read in a user-defined format. For more detailed information, see the following. D Displays the day as a number without leading zeros (such as 1). If this is the only character in the user-defined number format, use%d. DD Displays the day as a number with leading zeros (such as 01). The EEE displays the day as an abbreviated form (for example, Sun). EEEE Displays the day as the full name (for example, Sunday). M displays the month as a number without leading zeros (for example, January is represented as 1). If this is the only character in a user-defined number format, use%M. MM Displays the month as a number with leading zeros (for example, 01/12/01). MMM displays the month as an abbreviated form (for example, Jan). MMMM displays the month as a full month name (for example, January). GG Displays the era/era string (for example, A.D.) H uses a 12-hour system to display the hour as a number without leading zeros (for example, 1:15:15 PM). If this is a user-definedUnique characters in the number format, use%h. HH uses a 12-hour system to display the hour as a number with leading zeros (for example, 01:15:15 PM). H displays the hour as a number without leading zeros using a 24-hour system (for example, 1:15:15). If this is the only character in a user-defined number format, use%H. HH uses a 24-hour system to display the hour as a number with leading zeros (for example, 01:15:15). M displays the minute as a number without leading zeros (for example, 12:1:15). If this is the only character in a user-defined number format, use%m. MM Displays the minute as a number with leading zeros (for example, 12:01:15). s displays the seconds as a number without leading zeros (for example, 12:15:5). If this is the only character in a user-defined number format, use%s. The SS displays seconds as a number with leading zeros (for example, 12:15:05). F shows the decimal part of the second. For example, the FF will be accurately displayed to 1% seconds, and the FFFF will be displayed exactly one out of 10,000 seconds. You can use up to seven F symbols in a user-defined format. If this is the only character in a user-defined number format, use%f. T uses a 12-hour system, and displays uppercase A for any hour before noon, and displays uppercase P for any hour between noon and 11:59 p.m. If this is the only character in a user-defined number format, use%t. TT for a 12-hour locale, the uppercase AM is displayed for any hour before noon, and the uppercase PM is displayed for any hour between noon and 11:59 p.m. For locales that use the 24-hour format, no characters are displayed. Y Displays the year (0-9) as a number without leading zeros. If this is the only character in a user-defined number format, use%y. YY Displays the year, if applicable, in a two-digit number format with leading zeros. YYY Displays the year in four-digit number format. YYYY displays the year in four-digit number format. Z Displays the time zone offset without leading zeros (for example,-8). If this is the only character in a user-defined number format, use%z. ZZ Displays a time zone offset with a leading zero (for example, -08) ZZZ displays the full time zone offset (for example, -08:00) in the format display m/d/yy12/7/58d-mmm7-decd-mmmm-yy7-december-58d MMMM7 Decembermmmm yydecember 58hh:mm tt08:50 PMh:mm:ss t8:50:35 ph:mm20:50h:mm:ss20:50:35m/d/yyyy H:mm12/7/1958 20:50 IOS NSDate Date Operation Summary 1//Current time Create nSdate nsdate *mydate = [NSDate Date];        NSLog (@ "mydate =%@", mydate); 2//24 hours from now nstimeinterval secondsperday = 24*60*60;        NSDate *tomorrow = [NSDate datewithtimeintervalsincenow:secondsperday];        NSLog (@ "mydate =%@", tomorrow), 3//based on date created nstimeinterval secondsPerDay1 = 24*60*60;        NSDate *now = [NSDate Date];        NSDate *yesterday = [now addtimeinterval:-secondsperday1];  NSLog (@ "Yesterday =%@", yesterday);        4//comparison date BOOL samedate = [now isequaltodate:yesterday];        NSLog (@ "samedate =%lu", samedate);        4.1//get an earlier date nsdate *earlierdate = [Yesterday Earlierdate:now];        NSLog (@ "earlierdate =%@", earlierdate);        4.2//later date nsdate *laterdate = [Yesterday Laterdate:now];         NSLog (@ "laterdate =%@", laterdate);        Number of seconds between two dates nstimeinterval secondsbetweendates= [yesterday Timeintervalsincedate:now];        NSLog (@ "secondsbetweendates=%lf", secondsbetweendates); by NSCALendar class to create date nsdatecomponents *comp = [[Nsdatecomponentsalloc]init];        [Comp setmonth:06];        [Comp setday:01];        [Comp setyear:2001];        Nscalendar *mycal = [[Nscalendaralloc]initwithcalendaridentifier:nsgregoriancalendar];        NSDate *mydate1 = [MyCal Datefromcomponents:comp];         NSLog (@ "myDate1 =%@", myDate1); Get a date from an existing date unsigned units = nsmonthcalendarunit| Nsdaycalendarunit|        Nsyearcalendarunit;        Nsdatecomponents *COMP1 = [MyCal components:units fromdate:now];        Nsinteger month = [COMP1 month];        Nsinteger year = [COMP1 year];        Nsinteger day = [Comp1 day];        NSDateFormatter implementation date Output NSDateFormatter *formatter = [[Nsdateformatteralloc]init]; [Formatter setdatestyle:nsdateformatterfullstyle];//Direct output is the machine code//or manually set the style [formatter setdateformat:@ "YYYY-MM-DD"]        ;        NSString *string = [Formatter stringfromdate:now];        NSLog (@ "string =%@", string); NSLog (@ "formater =%@", formatter); Get date Format Object-(NSDateFormatter *) dateformatter {if (dateformatter = = nil) {dateformatter = [[NSDateFormatter alloc] init];[ Dateformatter Setdatestyle:nsdateformattermediumstyle]; [Dateformatter Settimestyle:nsdateformatternostyle];} return dateformatter;} Related usage of nsdate and NSDateFormatter 1.NSDateFormatter with the conversion between NSDate and NSString NSDateFormatter there are 2 ways:-(NSString *) Stringfromdate: (NSDate *) date;//nsdate turn NSString-(NSDate *) datefromstring: (NSString *) string;//nsstring to NSDate e.g. NSString *[email protected] "1900-01-01"; NSDateFormatter *dateformatter=[[nsdateformatter Alloc]init]; [Dateformatter setdateformat:@ "Yyyy-mm-dd"]; NSDate *date=[dateformatter datefromstring:datestring]; [Dateformatter release]; NSString to nsdate with some formats like NSString *datestring=[dateformatter datefromstring:[nsdate date]];2.nsdateformatter above [ Dateformatter setdateformat:@ "yyyy mm month DD day #eeee"];  Eeee for the day of the week, the Eee for weeks [dateformatter setdateformat:@ "Yyyy-mm-dd HH:mm:ss"]; [Dateformatter setdateformat:@ "yyyy year MMMMD Day"];//mmmm For XX months, a D can save 03 before 01th. NSString to NSDate less one day solution use the following format Method 1.   [Dateformatter setdateformat:@ "Yyyy-mm-dd HH:mm:ss"];   2. Nscalendar *calendar = [Nscalendar Currentcalendar]; nsdatecomponents *components = [Calendar components: (Nsdaycalendarunit |                                  Nsmonthcalendarunit |   Nsyearcalendarunit) fromdate:[nsdate [Date]]; NSDate *todaydate = [Calendar datefromcomponents:components];

  

Mode one background gives the format for yyyy-mm-DD HH:mm:ss. SSS on Code+ (NSString *) Comparecurrenttime: (NSString *) str{//Convert a string to NSDateNSDateFormatter *dateformatter =[[NSDateFormatter alloc] init]; [Dateformatter Setdateformat:@"yyyy-mm-dd HH:mm:ss. SSS"]; NSDate*timedate =[Dateformatter Datefromstring:str]; //get with current time differenceNstimeinterval timeinterval =[Timedate Timeintervalsincenow]; TimeInterval= -timeinterval; //Standard times and Beijing time difference 8 hoursTimeInterval = TimeInterval-8* -* -; Longtemp =0; NSString*result; if(TimeInterval < -) {result= [NSString stringWithFormat:@"just"]; }    Else if(temp = timeinterval/ -) < -) {result= [NSString stringWithFormat:@"%d minutes ago", temp]; }    Else if(temp = temp/ -) < -) {result= [NSString stringWithFormat:@"%d hours ago", temp]; }    Else if(temp = temp/ -) < -) {result= [NSString stringWithFormat:@"%d days ago", temp]; }    Else if(temp = temp/ -) < A) {result= [NSString stringWithFormat:@"%d months ago", temp]; }    Else{Temp= temp/ A; Result= [NSString stringWithFormat:@"%d years ago", temp]; }    returnresult;} Mode two background to the format for the pure number 1352170595000 (13 bit) on the code/** Returns the update time by the number of lines*/-(NSString *) Updatetimeforrow: (Nsinteger) Row {//gets the current time timestamp 1466386762.345715 10-bit integer 6-bit decimalNstimeinterval currenttime =[[NSDate Date] timeIntervalSince1970]; //Create a song timestamp (the time returned in the background is typically 13 digits)Nstimeinterval Createtime = self.model.tracks.list[row].createdat/ +; //Time DifferenceNstimeinterval time = currenttime-Createtime; //seconds to HourNsinteger hours = time/3600; if(hours< -) {        return[NSString stringWithFormat:@"%ld hours ago", hours]; }    //seconds Turn DaysNsinteger days = time/3600/ -; if(Days < -) {        return[NSString stringWithFormat:@"%ld days ago", days]; }    //seconds to monthNsinteger months = time/3600/ -/ -; if(Months < A) {        return[NSString stringWithFormat:@"%ld months ago", months]; }    //sec following yearNsinteger years = time/3600/ -/ -/ A; return[NSString stringWithFormat:@"%ld years ago", years];} Text/ios_ love OS (Jane book author) original link: http://www.jianshu.com/p/8c18c0c06e1aCopyright belongs to the author, please contact the author to obtain authorization, and Mark "book author".

Conversion of iOS time format

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.