NSDate, NSDateFormatter, Nsdatepicker Introduction

Source: Internet
Author: User
Tags gmt time zone benchmark dateformat instance method time zones julian day locale uicontrol

My life, my little drops.




#pragma mark.
NSDate Creation (example class method only, instance method)


Returns the current time (gmt,0 time Zone, GMT)
+ (ID) date;


Returns based on the current time and then secs seconds
+ (ID) Datewithtimeintervalsincenow: (nstimeinterval) secs;


Returns the benchmark with 2001/01/01 GMT and then secs seconds
+ (ID) datewithtimeintervalsincereferencedate: (Nstimeinterval) ti;


Returns the benchmark with 1970/01/01 GMT and then secs seconds
+ (ID) dateWithTimeIntervalSince1970: (nstimeinterval) secs;


Gets the corresponding time, based on the time interval and the specified date
+ (Instancetype) Datewithtimeinterval: (nstimeinterval) secstobeadded sincedate: (nsdate *) date;


Return to some day in the future many years later
+ (ID/* nsdate * * * *) distantfuture;


Return to a certain day many years ago
+ (ID/* nsdate * * * *) Distantpast;






#pragma mark.
nsdate Retrieve time interval
Takes Anotherdate as the base time, returns the time interval between the instance saved and the Anotherdate
-(Nstimeinterval) Timeintervalsincedate: (NSDate *) anotherdate;


Returns the time between the time the instance was saved and the current time (now) at the current time (now) as the base time
-(Nstimeinterval) Timeintervalsincenow;


Returns the time interval between the instance saved and the 1970/01/01 GMT with 1970/01/01 GMT as the base time
-(Nstimeinterval) timeIntervalSince1970;


Returns the time interval between the instance saved and the 2001/01/01 GMT with 2001/01/01 GMT as the base time
-(Nstimeinterval) timeintervalsincereferencedate;


Returns the time interval between the current time and 2001/01/01 GMT with 2001/01/01 GMT as the base time
+ (Nstimeinterval) timeintervalsincereferencedate;


#pragma mark.
nsdate Date Comparison
Returns the earlier date compared to the Anotherdate
-(NSDate *) Earlierdate: (NSDate *) anotherdate;


Returns the date that is later than the Anotherdate
-(NSDate *) Laterdate: (NSDate *) anotherdate;


The same returns yes, compared to anotherdate
-(BOOL) Isequaltodate: (NSDate *) otherdate;


Call when used for sort:
~ When the date value saved by the instance returns to Nsorderedsame with the other phase
~ When the date value saved by the instance is later than the other returns nsordereddescending
~ When the date value saved by the instance is earlier than the other returns nsorderedascending
-(Nscomparisonresult) Compare: (NSDate *) Other;


#pragma mark.
Mutual transformation of @NSString and NSDate (NSDateFormatter of the format series)


1. Convert String to date
Instantiate a NSDateFormatter object
NSDateFormatter * DateFormat = [[NSDateFormatter alloc] init];


Set the time format, pay attention to match the following datestring, or the date will be invalid
[DateFormat setdateformat:@ "Yyyy-mm-dd HH:mm:ss"];
NSDate *date =[dateformat datefromstring:@ "2013-3-11 10:00:01"];




2. Date to String
Instantiate a NSDateFormatter object
nsdateformatter* DateFormat = [[NSDateFormatter alloc] init];
Set locale, the day of the week will be displayed in Chinese
Dateformat.locale = [[Nslocale alloc] initwithlocaleidentifier:@ "ZH_CN"];
Set time format (followed by a, default is Chinese)
[DateFormat setdateformat:@ "Yyyy-mm-dd HH:mm:ss a"];
Monday, last afternoon, etc. shown as English, the am,pm into the morning, the afternoon display as Chinese
[DateFormat setamsymbol:@ "AM"];
[DateFormat setpmsymbol:@ "PM"];
System default Format
[DateFormat Setdatestyle:nsdateformatterfullstyle];
[DateFormat Settimestyle:nsdateformatterfullstyle];
Find the time string for the day, and the time string changes as you change the time format
NSString *datestring = [DateFormat stringfromdate:[nsdate Date]];




@NSDateFormatter format string corresponding table


A:AM/PM (a.m./PM)


a:0~86399999 (First a microsecond of the day)


C/cc:1~7 (first day of the week, Sunday is 1)


Ccc:sun/mon/tue/wed/thu/fri/sat (abbreviated days of the week)


Cccc:sunday/monday/tuesday/wednesday/thursday/friday/saturday (week full spell)


D:1~31 (Day of the month, with 0)


d:1~366 (Day of the Year, with 0)


E:1~7 (Day of the week, with 0)


E~eee:sun/mon/tue/wed/thu/fri/sat (abbreviated days of the week)


Eeee:sunday/monday/tuesday/wednesday/thursday/friday/saturday (week full spell)


F:1~5 (Week of the month, first day of the week is Monday)


G:julian Day number (number of days since 4713 BC January 1) Unknown


G~ggg:bc/ad (Era designator abbreviated) unknown


Gggg:before Christ/anno Domini Unknown


H:1~12 (0 padded Hour (12hr)) with 0, 12-hour system


h:0~23 (0 padded Hour (24hr)) with 0, 24-hour system


K:1~24 (0 padded Hour (24hr) with 0, 24-hour system


K:0~11 (0 padded Hour (12hr)) with 0, 12-hour system


L/LL:1~12 (0 padded Month) month (3)


Lll:jan/feb/mar/apr/may/jun/jul/aug/sep/oct/nov/dec month abbreviation (March)


Llll:january/february/march/april/may/june/july/august/september/october/november/december Month Full name (March)


m:0~59 (0 padded Minute) minutes


M/MM:1~12 (0 padded Month) first few months


Mmm:jan/feb/mar/apr/may/jun/jul/aug/sep/oct/nov/dec


Mmmm:january/february/march/april/may/june/july/august/september/october/november/december (with Llll)


Q/qq:1~4 (0 padded quarter) The first few quarters


QQQ:Q1/Q2/Q3/Q4 Quarterly abbreviation


qqqq:1st quarter/2nd quarter/3rd quarter/4th Quarter Quarter full spell


Q/qq:1~4 (0 padded quarter) with lowercase


Qqq:q1/q2/q3/q4 with lowercase


qqqq:1st quarter/2nd quarter/3rd quarter/4th Quarter with lowercase


s:0~59 (0 padded Second) seconds


S: (rounded sub-second) unknown


U: (0 padded year) unknown


V~VVV: (general GMT Timezone abbreviation) Preparation of regular GMT time zones


VVVV: (general GMT Timezone name) The name of the regular GMT time zone


w:1~53 (0 padded Week, 1st day of Week = Sunday, nb:1st Week of year starts from the last Sunday The first weeks of the year, the beginning of the week of Sunday, the start of the last Sunday


W:1~5 (0 padded Week of Month, 1st day of Week = Sunday) First weeks of one months


Y/YYYY: Full year


YY/YYY: (2 Digits year) 2 number of years


Y/YYYY: (full years, starting from the Sunday of the 1st week of) this year is unknown.


YY/YYY: (2 Digits years, starting from the Sunday of the 1st week of) this year is unknown.


Z~zzz: (Specific GMT Timezone abbreviation) Specify the writing of GMT time zone


ZZZZ: (Specific GMT Timezone name) Z: +0000 (RFC 822 Timezone) Specify the name of the GMT time zone




Uidatepicker is a controller class that encapsulates Uipickerview, but is a subclass of Uicontrol that is designed to accept dates, times, and durations of input. His fixed height of 216 can't be changed,

He did not provide changes in the font color or font size of the interface, although very uncomfortable, but still useful.




Uidatepicker depends on the NSDate class.

First, create date/Time picker


Uidatepicker is simpler to use than standard Uipickerview. He will create his own data source based on the date range you specify, using it to create only one object:


Uidatepicker *datepicker = [[Uidatepicker alloc] Initwithframe:cgrectmake (0.0,0.0,0.0,0.0)];

By default, selection displays the current date and time, and provides several dials, showing the month and date, hour, minute, and morning and afternoon, respectively, that can be selected.

Therefore, the user can select any combination of dates and times by default.


Second, date selector mode


The date/time Picker supports the choice of 4 different modes, by setting the Datepickermode property, you can define the selection mode:


Datepicker.datepickermode = Uidatepickermodetime;


Supported modes:


typedef enum {
Uidatepickermodetime, displays only the time, does not display the date

Uidatepickermodedate, displays only the date, does not show the time

Uidatepickermodedateandtime, displaying both date and time

Uidatepickermodecountdowntimer countdown timer hours and minutes
} Uidatepickermode;

Three, time interval


You can set the clock to display minutes at different intervals, provided that the interval is divisible by 60, and the default minimum interval is one minute, and if you want to use a different interval,

You need to change the Minuteinterval property:


Datepicker.minuteinterval = 5;


Four, date range


You can specify the date range to use by setting the Mininumdate and Maxinumdate properties. If the user attempts to scroll to a date beyond this range, the dial rolls back to the nearest

The valid date for the

, two methods require the NSDate object as a parameter:


nsdate* mindate = [[NSDate alloc]initwithstring:@] 1900-01-01 00:00:00 +0800 ]; &NBSP
nsdate* maxdate = [NSDate alloc]initwithstring:@ "2099-01-01 00:00:00 +0800"];  
       
Datepicker.minimumdate = mindate;  
datepicker.maximumdate = MaxDate;  


If any of the two date range properties are not set, the default behavior will allow the user to select any date in the past or future. This is useful in some cases, for example, when you select

Birthdays can be any date in the past, but end with the current date. If you want to set the default display date, you can use the Date property:


Datepicker.date = MinDate;


In addition, you can also use the Setdate method. If you choose to use animation, the dial will scroll to the date you specify:


[DatePicker setdate:maxdate Animated:yes];

Five, display date selector


[Self.view Addsubview:datepicker];


It should be noted that the picker's height is always 216 pixels, to be sure that enough space is allocated to accommodate it.


Vi. Date of Reading


nsdate* _date = datepicker.date;


Because the date selector is a subclass of Uicontrol (unlike Uipickerview), you can also hook up a delegate in the notification structure of the Uicontrol class:




[DatePicker addtarget:self Action: @selector (datechanged:) forcontrolevents:uicontroleventvaluechanged];

As soon as the user chooses a new date, your action class is called:


-(void) datechanged: (ID) sender
{  
    uidatepicker* control = (uidatepicker*) sender;  
    nsdate* _date = control.date;  
    /* Add your own response code */  
}  


However, since DatePicker does not provide any interface to change its style, if you want to make other patterns or change the color of an element inside it, you have to use Pickview customization.


Example: Countdown timer


Set the Uidatepicker mode to count down timer for the control to be used as a countdown timer. When Uidatepicker is used as a countdown timer, the program should also

Start a timer to periodically update the remaining time for the Uidatepicker. Thus, when using Uidatepicker as the count down timer mode, the most important genus of the control

Sex is Countdownduration, the property represents the remainder of the countdown, and the program can get the remaining time of the control through the Countdownduration property, or through the

Modify the property to change the time remaining for the control to display.


Look at the example below, the interface last button, a DatePicker


nstimer* timer;  Nsinteger Leftseconds;
    ①-(void) viewdidload {[Super viewdidload];
Set use count down Timer mode self.countDown.datePickerMode = Uidatepickermodecountdowntimer;
	
    }-(Ibaction) clicked: (ID) Sender {//Get the remainder of the countdown timer leftseconds = self.countDown.countDownDuration;
    Disable Uidatepicker controls and buttons self.countDown.enabled = NO;
	
    [Sender Setenabled:no]; Initializes a string nsstring *message = [NSString stringWithFormat: @] begins the countdown.
		
    You have "%d" seconds left, Leftseconds]; Create a Uialertview (warning box) Uialertview *alert = [[Uialertview alloc] initwithtitle:@ "Start the countdown. "Message:message Delegate:nil cancelbuttontitle:@
						
    "Determine" otherbuttontitles:nil];
	
    Display the Uialertview control [alert show]; Enable the timer to control every 60 seconds Tickdown method timer = [Nstimer scheduledtimerwithtimeinterval:60 target:self selector: @select or (Tickdown) USErinfo:nil Repeats:yes];  }-(void) Tickdown {leftseconds = 60;  Reduce the remaining time by 60 seconds self.countDown.countDownDuration = Leftseconds;
        Modify the remaining time of Uidatepicker if (leftseconds <= 0)//If the remaining time is less than or equal to 0 {//cancel timer [timer invalidate];
        Enable Uidatepicker controls and buttons self.countDown.enabled = YES;
    self.startBn.enabled = YES; }
}




In the above program, the ① code defines a leftseconds variable that holds the time remaining for the countdown timer, which fires when the user clicks the program interface.

Clicked: Method, which starts a timer control to perform a Tickdown method every 60 seconds, and the Tickdown method executes the remainder of the countdown timer every time

Time is reduced by 60 and the remaining time of the countdown is dynamically modified so that the remaining time shown by Uidatepicker can be reduced.



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.