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
= [ NSCalendar currentCalendar]; NSDateComponents *components; int unitFlags; float sysVersion
= [[[UIDevice currentDevice] systemVersion]floatValue]; if (sysVersion
>= 8.0) { unitFlags
= NSCalendarUnitYear |
NSCalendarUnitMonth |
NSCalendarUnitDay ; } else { unitFlags
= NSYearCalendarUnit |
NSMonthCalendarUnit |
NSDayCalendarUnit ; } components
= [calendar components:unitFlags fromDate:date toDate:[ NSDate date] options:0]; long year
= [components year]; long month
= [components month]; long day
= [components day]; |
1
2
3
4
5
6
7
8
9
10
11
|
//设置源日期时区 NSTimeZone *
sourceTimeZone = [ NSTimeZone timeZoneWithAbbreviation:@ "UTC" ]; //或GMT //设置转换后的目标日期时区 NSTimeZone *
destinationTimeZone = [ NSTimeZone localTimeZone]; //得到源日期与世界标准时间的偏移量 NSInteger sourceGMTOffset
= [sourceTimeZone secondsFromGMTForDate:anyDate]; //目标日期与本地时区的偏移量 NSInteger destinationGMTOffset
= [destinationTimeZone secondsFromGMTForDate:anyDate]; //得到时间偏移量的差值 NSTimeInterval interval
= destinationGMTOffset - sourceGMTOffset; NSLog (@ "%f" ,
interval/60/60); //
8.000000 |
1
2
3
4
5
6
7
8
9
|
//
计算日期差 NSString *currentTimestamp
= [ NSString stringWithFormat:@ "%ld" ,
( long )[currentDate
timeIntervalSince1970]]; NSString *fromDay
= [ self getStringDateFormatterWithTimestamp:timestamp
byFormat:@ "dd" ]; NSString *toDay
= [ self getStringDateFormatterWithTimestamp:currentTimestamp
byFormat:@ "dd" ]; int from
= [fromDay intValue]; int to
= [toDay intValue]; return to
- from; |
1
2
3
4
5
6
7
8
|
//
格式转换 +
( NSString *)getStringDateFormatterWithTimestamp:( NSString *)timestamp
byFormat:( NSString *)format
{ NSDateFormatter *formatter
= [[ NSDateFormatter alloc]
init]; [formatter
setDateFormat:[ NSString stringWithFormat:@ "%@" ,
format]]; NSDate *date
= [ NSDate dateWithTimeIntervalSince1970:[timestamp
doubleValue]]; NSString *dateStr
= [formatter stringFromDate:date]; return dateStr; } |
1
|
let
isToday = calendar.isDateInToday(date) |
1
2
3
4
5
6
7
8
9
10
|
NSCalendar *calendar
= [ NSCalendar currentCalendar]; BOOL isToday
= [calendar isDateInToday:[ NSDate dateWithTimeIntervalSince1970:[timestamp
doubleValue]]]; BOOL isYesterday
= [calendar isDateInYesterday:[ NSDate dateWithTimeIntervalSince1970:[timestamp
doubleValue]]]; if (isToday)
{ return 0; } if (isYesterday)
{ return 1; } return -1; |
原文地址:http://blog.csdn.net/longshiqing14/article/details/45873439