iOS上的选择时间日期的控件是这样的,左边是时间和日期混合,右边是单纯的日期模式。
, 
您可以选择自己需要的模式,Time, Date,Date and Time , Count Down Timer四种模式。

本篇文章简单介绍下PickerDate控件的使用
1、新建一个Singe View Application,命名为DatePickDemo,其他设置如图

2、放置控件
打开ViewController.xib,拖拽一个DatePicker控件放到界面上,再拖拽一个Button控件放到界面上,双击Button,输入"选择日期时间"

3、建立xib和ViewController的关联
按下command+alt+enter键打开Assistant Editor,选中DatePicker按住Control键,拖拽到viewController.h上,

建立Outlet datePicker。
以同样方式给Button建立一个Action关联映射,命名为selectDate,事件类型为默认的Touch Up Inside。
4、实现代码
- (IBAction)selectDate:(id)sender {
}
在这里添加响应代码

5、修改模式成Date模式,修改代码

|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
NSCalendar*calendar
= [NSCalendarcurrentCalendar]; NSDateComponents*components; intunitFlags; floatsysVersion
= [[[UIDevice currentDevice] systemVersion]floatValue]; if(sysVersion
>= 8.0) { unitFlags
= NSCalendarUnitYear|
NSCalendarUnitMonth|
NSCalendarUnitDay; }else{ unitFlags
= NSYearCalendarUnit|
NSMonthCalendarUnit|
NSDayCalendarUnit; } components
= [calendar components:unitFlags fromDate:date toDate:[NSDatedate] options:0]; longyear
= [components year]; longmonth
= [components month]; longday
= [components day]; |
|
1
2
3
4
5
6
7
8
9
10
11
|
//设置源日期时区 NSTimeZone*
sourceTimeZone = [NSTimeZonetimeZoneWithAbbreviation:@"UTC"];//或GMT //设置转换后的目标日期时区 NSTimeZone*
destinationTimeZone = [NSTimeZonelocalTimeZone]; //得到源日期与世界标准时间的偏移量 NSIntegersourceGMTOffset
= [sourceTimeZone secondsFromGMTForDate:anyDate]; //目标日期与本地时区的偏移量 NSIntegerdestinationGMTOffset
= [destinationTimeZone secondsFromGMTForDate:anyDate]; //得到时间偏移量的差值 NSTimeIntervalinterval
= destinationGMTOffset - sourceGMTOffset; NSLog(@"%f",
interval/60/60); //
8.000000 |
|
1
2
3
4
5
6
7
8
9
|
//
计算日期差 NSString*currentTimestamp
= [NSStringstringWithFormat:@"%ld",
(long)[currentDate
timeIntervalSince1970]]; NSString*fromDay
= [selfgetStringDateFormatterWithTimestamp:timestamp
byFormat:@"dd"]; NSString*toDay
= [selfgetStringDateFormatterWithTimestamp:currentTimestamp
byFormat:@"dd"]; intfrom
= [fromDay intValue]; intto
= [toDay intValue]; returnto
- from; |
|
1
2
3
4
5
6
7
8
|
//
格式转换+
(NSString*)getStringDateFormatterWithTimestamp:(NSString*)timestamp
byFormat:(NSString*)format
{ NSDateFormatter*formatter
= [[NSDateFormatteralloc]
init]; [formatter
setDateFormat:[NSStringstringWithFormat:@"%@",
format]]; NSDate*date
= [NSDatedateWithTimeIntervalSince1970:[timestamp
doubleValue]]; NSString*dateStr
= [formatter stringFromDate:date]; returndateStr;} |
|
1
|
let
isToday = calendar.isDateInToday(date) |
|
1
2
3
4
5
6
7
8
9
10
|
NSCalendar*calendar
= [NSCalendarcurrentCalendar]; BOOLisToday
= [calendar isDateInToday:[NSDatedateWithTimeIntervalSince1970:[timestamp
doubleValue]]]; BOOLisYesterday
= [calendar isDateInYesterday:[NSDatedateWithTimeIntervalSince1970:[timestamp
doubleValue]]]; if(isToday)
{ return0; } if(isYesterday)
{ return1; } return-1; |
原文地址:http://blog.csdn.net/longshiqing14/article/details/45873439