NSDate对象包含两个部分,日期(Date)和时间(Time)。格式化的时间字符串主要也是针对日期和时间的
1、基础用法
NSDate* now = [NSDate date];
NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
fmt.dateStyle = kCFDateFormatterShortStyle;
fmt.timeStyle = kCFDateFormatterShortStyle;
fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
NSString* dateString = [fmt stringFromDate:now];
NSLog(@"%@", dateString);
[fmt release];
打印输出:10/29/12, 2:27 PM
这使用的系统提供的格式化字符串,通过 fmt.dateStyle 和 fmt.timeStyle 进行的设置。实例中使用的参数是 kCFDateFormatterShortStyle,此外还有:
typedef CF_ENUM(CFIndex, CFDateFormatterStyle) { // date and time format styles
kCFDateFormatterNoStyle = 0, // 无输出
kCFDateFormatterShortStyle = 1, // 10/29/12, 2:27 PM
kCFDateFormatterMediumStyle = 2, // Oct 29, 2012, 2:36:59 PM
kCFDateFormatterLongStyle = 3, // October 29, 2012, 2:38:46 PM GMT+08:00
kCFDateFormatterFullStyle = 4 // Monday, October 29, 2012, 2:39:56 PM China Standard Time
};
自己写的date转换成nsstring:
2. 自定义区域语言
如上实例中,我们使用的是区域语言是 en_US,指的是美国英语。如果我们换成简体中文,则代码是:
fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
则对应的输出为:
typedef CF_ENUM(CFIndex, CFDateFormatterStyle) { // date and time format styles
kCFDateFormatterNoStyle = 0, // 无输出
kCFDateFormatterShortStyle = 1, // 12-10-29 下午2:52
kCFDateFormatterMediumStyle = 2, // 2012-10-29 下午2:51:43
kCFDateFormatterLongStyle = 3, // 2012年10月29日 GMT+0800下午2时51分08秒
kCFDateFormatterFullStyle = 4 // 2012年10月29日星期一 中国标准时间下午2时46分49秒
};
世界通用的区域语言代码,详见 International Components for Unicode (ICU), http://userguide.icu-project.org/formatparse/datetime
3. 自定义日期时间格式
NSDateFormatter提供了自定义日期时间的方法,主要是通过设置属性 dateFormat,常见的设置如下:
NSDate* now = [NSDate date];
NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
fmt.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss";
NSString* dateString = [fmt stringFromDate:now];
NSLog(@"%@", dateString);
[fmt release];
打印输出:2012-10-29T16:08:40
除了上面列出的,还可以指定很多格式,详见http://userguide.icu-project.org/formatparse/datetime。
结合设置Locale,还可以打印出本地化的字符串信息。
NSDate* now = [NSDate date];
NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
fmt.dateFormat = @"yyyy-MM-dd a HH:mm:ss EEEE";
NSString* dateString = [fmt stringFromDate:now];
NSLog(@"\n%@", dateString);
[fmt release];
打印输出:2012-10-29 下午 16:25:27 星期一
4. 自定义月份星期等字符
NSDateFormatter中同样提供了相应的方式,去修改这些字符。一般情况下,使用相应区域语言下面的默认字符就OK了。但是你的确有这个需求,那么也是可以办到的。相应的方法非常多,如下:
Managing AM and PM Symbols
– AMSymbol
– setAMSymbol:
– PMSymbol
– setPMSymbol:
Managing Weekday Symbols
– weekdaySymbols
– setWeekdaySymbols:
– shortWeekdaySymbols
– setShortWeekdaySymbols:
– veryShortWeekdaySymbols
– setVeryShortWeekdaySymbols:
– standaloneWeekdaySymbols
– setStandaloneWeekdaySymbols:
– shortStandaloneWeekdaySymbols
– setShortStandaloneWeekdaySymbols:
– veryShortStandaloneWeekdaySymbols
– setVeryShortStandaloneWeekdaySymbols:
Managing Month Symbols
– monthSymbols
– setMonthSymbols:
– shortMonthSymbols
– setShortMonthSymbols:
– veryShortMonthSymbols
– setVeryShortMonthSymbols:
– standaloneMonthSymbols
– setStandaloneMonthSymbols:
– shortStandaloneMonthSymbols
– setShortStandaloneMonthSymbols:
– veryShortStandaloneMonthSymbols
– setVeryShortStandaloneMonthSymbols:
Managing Quarter Symbols
– quarterSymbols
– setQuarterSymbols:
– shortQuarterSymbols
– setShortQuarterSymbols:
– standaloneQuarterSymbols
– setStandaloneQuarterSymbols:
– shortStandaloneQuarterSymbols
– setShortStandaloneQuarterSymbols:
Managing Era Symbols
– eraSymbols
– setEraSymbols:
– longEraSymbols
– setLongEraSymbols:
date转换成nsstring方法:
- (NSString *)dateFromString:(NSString *)dateString
{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [dateFormat dateFromString:dateString];
[dateFormat setDateFormat:@"yyyy-MM-dd"];
NSString *srting = [dateFormat stringFromDate:date];
[dateFormat release];
return srting;
}
带样式的时间转换
- (NSString *)dateFromStringWithDateStyle:(NSDateFormatterStyle)dateStyle
{
NSDate* now = [NSDate date];
NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
fmt.dateStyle = dateStyle;
fmt.timeStyle = dateStyle;
fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
NSString* dateString = [fmt stringFromDate:now];
[fmt release];
return dateString;
}
#pragma mark ===============常用的宏定义================
#define kScreenHeight [[UIScreen mainScreen] bounds].size.height
#define kScreenWidth [[UIScreen mainScreen] bounds].size.width
#define kStateBarHeight 20
#define kMainHeight (ScreenHeight - StateBarHeight)
#define kMainWidth ScreenWidth
#define kIsIPhone5 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size) : NO)
#define BACKGROUND_CORLOR [UIColor colorWithRed:222.0/255 green:222.0/255 blue:222.0/255 alpha:1]
#define kUserDefault [NSUserDefaults standardUserDefaults]
#define kApplication [UIApplication sharedApplication]
#define kDataEnv [DataEnvironment sharedDataEnvironment]
#define kDegreesToRadian(x) (M_PI * (x) / 180.0)
#define kRadianToDegrees(radian) (radian*180.0)/(M_PI)
#define kRgbColor(r,g,b) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:1]
#define kRgbColor2(r,g,b,a) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:(a)]
/* 根据名称加载有缓存图片 */
#define kImageNamed(name) [UIImage imageNamed:name]
//判断系统的当然版本。
#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#pragma mark ===============不常用的宏定义================
#define kSystemError @"系统繁忙,请稍后再试!"
/* 获取系统目录 */
#define kGetDirectory(NSSearchPathDirectory) [NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory, NSUserDomainMask, YES)lastObject]
/* 获取NSFILEMANAGER对象 */
#define kFileManager [NSFileManager defaultManager]
/* 获取程序代理 */
#define kAppdelegate ((AppDelegate *)[[UIApplication sharedApplication] delegate])
/* 获取任意WINDOW对象 */
#define kWindow [[[UIApplication sharedApplication] windows] lastObject]
/* 获取KEYWINDOW对象 */
#define kKeyWindow [[UIApplication sharedApplication] keyWindow]
/* 获取USERDEFAULTS对象 */
#define kNotificactionCenter [NSNotificationCenter defaultCenter]
/* 获取当前控制器的navigationBar */
#define kNavigationBar [[self navigationController] navigationBar]
/* 简单提示框 */
#define kAlert(title, msg) [[[UIAlertView alloc] initWithTitle:title message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil]show]
/*------------------------------------加载图片---------------------------------------*/
/* 根据名称加载无缓存图片 */
#define kNoCacheImagewithName(name, ext) [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]pathForResource:name ofType:ext]]
/* 根据路径加载无缓存图片 */
#define kNoCacheImagewithPath(path) [UIImage imageWithContentsOfFile:path]
/*------------------------------------视图------------------------------------------*/
/* 根据TAG获取视图 */
#define kViewWithTag(PARENTVIEW, TAG, CLASS) ((CLASS *)[PARENTVIEW viewWithTag:TAG])
/* 加载NIB文件 */
#define kLOADNIBWITHNAME(CLASS, OWNER) [[[NSBundle mainBundle] loadNibNamed:CLASS owner:OWNER options:nil] lastObject]
/* 异步 */
#define kGCDAsync(block) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), block)
/* 同步 */
#define kGCDMain(block) dispatch_async(dispatch_get_main_queue(),block)
/*-----------------------------------界面尺寸--------------------------------------*/
/* 导航栏高度 */
#define kNavigationBarHeight 44
/* 工具栏高度 */
#define kTabBarHeight 49
/* 是否IPad */
#define kIsIpad (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
/* 是否IPhone */
#define kIsIphone (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
/* 获取系统信息 */
#define kSystemVersion [[UIDevice currentDevice] systemVersion]
/* 获取当前语言环境 */
#define kCurrentLanguage [[NSLocale preferredLanguages] objectAtIndex:0]
/* 获取当前APP版本 */
#define kAppVersion [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]
/*-----------------------------------调试相关--------------------------------------*/
#ifdef DEBUG
#define XLOG(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
#define XLOG(...);
#endif
在一些系统开发中(例如机顶盒)有可能遇到需求不响应鼠标按键,在开发中怎么解决呢?下面我来给大家演示:
1.系统中按键的响应都是通过在ViewRootImpl中传递给View的,所以要想屏蔽按键就要在ViewRootImpl.java中寻找;
2.在setView中sWindowSession.add(mWindow, mSeq, mWindowAttributes,getHostVisibility(), mAttachInfo.mContentInsets,mInputChannel);建立View与WMS的联系这样WMS就能把消息传递给View了,但是怎么传递的呢?答案是:mInputChannel.
注册:
if (mInputChannel != null) { if (mInputQueueCallback != null) { mInputQueue = new InputQueue(mInputChannel); mInputQueueCallback.onInputQueueCreated(mInputQueue); } else { InputQueue.registerInputChannel(mInputChannel, mInputHandler, Looper.myQueue()); } }
响应回掉处理:
private final InputHandler mInputHandler = new InputHandler() { public void handleKey(KeyEvent event, InputQueue.FinishedCallback finishedCallback) { startInputEvent(finishedCallback); dispatchKey(event, true);//处理按键 } public void handleMotion(MotionEvent event, InputQueue.FinishedCallback finishedCallback) { startInputEvent(finishedCallback); dispatchMotion(event, true);//处理触摸,鼠标,摇杆等消息 } };3.下面看dispatchMotion函数:
private void dispatchMotion(MotionEvent event, boolean sendDone) { int source = event.getSource(); if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { Log.d(TAG,"----dispatchPointer----"); dispatchPointer(event, sendDone);//在有鼠标点击事件时会调用 } else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) { dispatchTrackball(event, sendDone); Log.d(TAG,"----dispatchTrackball----"); } else { dispatchGenericMotion(event, sendDone); Log.d(TAG,"----dispatchGenericMotion----"); } }看dispatchPointer函数,其实里面就是发送了DISPATCH_POINTER消息真正处理是在deliverPointerEvent函数;所以只需要在deliverPointerEvent函数中处理,具体代码:
finishMotionEvent(event, sendDone, true); return;