#import <Foundation/Foundation.h>
@interface NSDate (Helpers)
@end
#import "Date.h"

@implementation NSDate(Helpers)

//获取年月日如:19871127.
- (NSString *)getFormatYearMonthDay
{
NSString *string = [NSString stringWithFormat:@"%d%02d%02d",[self getYear],[self getMonth],[self getDay]];
return string;
} //该日期是该年的第几周
- (int )getWeekOfYear
{
int i;
int year = [self getYear];
NSDate *date = [self endOfWeek];
for (i = ;[[date dateAfterDay:- * i] getYear] == year;i++)
{
}
return i;
}
//返回day天后的日期(若day为负数,则为|day|天前的日期)
- (NSDate *)dateAfterDay:(int)day
{
NSCalendar *calendar = [NSCalendar currentCalendar];
// Get the weekday component of the current date
// NSDateComponents *weekdayComponents = [calendar components:NSWeekdayCalendarUnit fromDate:self];
NSDateComponents *componentsToAdd = [[NSDateComponents alloc] init];
// to get the end of week for a particular date, add (7 - weekday) days
[componentsToAdd setDay:day];
NSDate *dateAfterDay = [calendar dateByAddingComponents:componentsToAdd toDate:self options:];
[componentsToAdd release]; return dateAfterDay;
}
//month个月后的日期
- (NSDate *)dateafterMonth:(int)month
{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *componentsToAdd = [[NSDateComponents alloc] init];
[componentsToAdd setMonth:month];
NSDate *dateAfterMonth = [calendar dateByAddingComponents:componentsToAdd toDate:self options:];
[componentsToAdd release]; return dateAfterMonth;
}
//获取日
- (NSUInteger)getDay{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dayComponents = [calendar components:(NSDayCalendarUnit) fromDate:self];
return [dayComponents day];
}
//获取月
- (NSUInteger)getMonth
{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dayComponents = [calendar components:(NSMonthCalendarUnit) fromDate:self];
return [dayComponents month];
}
//获取年
- (NSUInteger)getYear
{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dayComponents = [calendar components:(NSYearCalendarUnit) fromDate:self];
return [dayComponents year];
}
//获取小时
- (int )getHour {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSUInteger unitFlags =NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit |NSHourCalendarUnit|NSMinuteCalendarUnit;
NSDateComponents *components = [calendar components:unitFlags fromDate:self];
NSInteger hour = [components hour];
return (int)hour;
}
//获取分钟
- (int)getMinute {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSUInteger unitFlags =NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit |NSHourCalendarUnit|NSMinuteCalendarUnit;
NSDateComponents *components = [calendar components:unitFlags fromDate:self];
NSInteger minute = [components minute];
return (int)minute;
}
- (int )getHour:(NSDate *)date {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSUInteger unitFlags =NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit |NSHourCalendarUnit|NSMinuteCalendarUnit;
NSDateComponents *components = [calendar components:unitFlags fromDate:date];
NSInteger hour = [components hour];
return (int)hour;
}
- (int)getMinute:(NSDate *)date {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSUInteger unitFlags =NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit |NSHourCalendarUnit|NSMinuteCalendarUnit;
NSDateComponents *components = [calendar components:unitFlags fromDate:date];
NSInteger minute = [components minute];
return (int)minute;
}
//在当前日期前几天
- (NSUInteger)daysAgo {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSDayCalendarUnit)
fromDate:self
toDate:[NSDate date]
options:];
return [components day];
}
//午夜时间距今几天
- (NSUInteger)daysAgoAgainstMidnight {
// get a midnight version of ourself:
NSDateFormatter *mdf = [[NSDateFormatter alloc] init];
[mdf setDateFormat:@"yyyy-MM-dd"];
NSDate *midnight = [mdf dateFromString:[mdf stringFromDate:self]];
[mdf release]; return (int)[midnight timeIntervalSinceNow] / (**) *-;
} - (NSString *)stringDaysAgo {
return [self stringDaysAgoAgainstMidnight:YES];
} - (NSString *)stringDaysAgoAgainstMidnight:(BOOL)flag {
NSUInteger daysAgo = (flag) ? [self daysAgoAgainstMidnight] : [self daysAgo];
NSString *text = nil;
switch (daysAgo) {
case :
text = @"Today";
break;
case :
text = @"Yesterday";
break;
default:
text = [NSString stringWithFormat:@"%d days ago", daysAgo];
}
return text;
} //返回一周的第几天(周末为第一天)
- (NSUInteger)weekday {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *weekdayComponents = [calendar components:(NSWeekdayCalendarUnit) fromDate:self];
return [weekdayComponents weekday];
}
//转为NSString类型的
+ (NSDate *)dateFromString:(NSString *)string {
return [NSDate dateFromString:string withFormat:[NSDate dbFormatString]];
} + (NSDate *)dateFromString:(NSString *)string withFormat:(NSString *)format {
NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setDateFormat:format];
NSDate *date = [inputFormatter dateFromString:string];
[inputFormatter release];
return date;
} + (NSString *)stringFromDate:(NSDate *)date withFormat:(NSString *)format {
return [date stringWithFormat:format];
} + (NSString *)stringFromDate:(NSDate *)date {
return [date string];
} + (NSString *)stringForDisplayFromDate:(NSDate *)date prefixed:(BOOL)prefixed {
/*
* if the date is in today, display 12-hour time with meridian,
* if it is within the last 7 days, display weekday name (Friday)
* if within the calendar year, display as Jan 23
* else display as Nov 11, 2008
*/ NSDate *today = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *offsetComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit |NSDayCalendarUnit)
fromDate:today]; NSDate *midnight = [calendar dateFromComponents:offsetComponents]; NSDateFormatter *displayFormatter = [[NSDateFormatter alloc] init];
NSString *displayString = nil; // comparing against midnight
if ([date compare:midnight] == NSOrderedDescending) {
if (prefixed) {
[displayFormatter setDateFormat:@"'at' h:mm a"]; // at 11:30 am
} else {
[displayFormatter setDateFormat:@"h:mm a"]; // 11:30 am
}
} else {
// check if date is within last 7 days
NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init];
[componentsToSubtract setDay:-];
NSDate *lastweek = [calendar dateByAddingComponents:componentsToSubtract toDate:today options:];
[componentsToSubtract release];
if ([date compare:lastweek] == NSOrderedDescending) {
[displayFormatter setDateFormat:@"EEEE"]; // Tuesday
} else {
// check if same calendar year
NSInteger thisYear = [offsetComponents year]; NSDateComponents *dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit |NSDayCalendarUnit)
fromDate:date];
NSInteger thatYear = [dateComponents year];
if (thatYear >= thisYear) {
[displayFormatter setDateFormat:@"MMM d"];
} else {
[displayFormatter setDateFormat:@"MMM d, yyyy"];
}
}
if (prefixed) {
NSString *dateFormat = [displayFormatter dateFormat];
NSString *prefix = @"'on' ";
[displayFormatter setDateFormat:[prefix stringByAppendingString:dateFormat]];
}
} // use display formatter to return formatted date string
displayString = [displayFormatter stringFromDate:date];
[displayFormatter release];
return displayString;
} + (NSString *)stringForDisplayFromDate:(NSDate *)date {
return [self stringForDisplayFromDate:date prefixed:NO];
} - (NSString *)stringWithFormat:(NSString *)format {
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateFormat:format];
NSString *timestamp_str = [outputFormatter stringFromDate:self];
[outputFormatter release];
return timestamp_str;
} - (NSString *)string {
return [self stringWithFormat:[NSDate dbFormatString]];
} - (NSString *)stringWithDateStyle:(NSDateFormatterStyle)dateStyle timeStyle:(NSDateFormatterStyle)timeStyle {
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateStyle:dateStyle];
[outputFormatter setTimeStyle:timeStyle];
NSString *outputString = [outputFormatter stringFromDate:self];
[outputFormatter release];
return outputString;
}
//返回周日的的开始时间
- (NSDate *)beginningOfWeek {
// largely borrowed from "Date and Time Programming Guide for Cocoa"
// we'll use the default calendar and hope for the best NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *beginningOfWeek = nil;
BOOL ok = [calendar rangeOfUnit:NSWeekCalendarUnit startDate:&beginningOfWeek
interval:NULL forDate:self];
if (ok) {
return beginningOfWeek;
} // couldn't calc via range, so try to grab Sunday, assuming gregorian style
// Get the weekday component of the current date
NSDateComponents *weekdayComponents = [calendar components:NSWeekdayCalendarUnit fromDate:self]; /*
Create a date components to represent the number of days to subtract from the current date.
The weekday value for Sunday in the Gregorian calendar is 1, so subtract 1 from the number of days to subtract from the date in question. (If today's Sunday, subtract 0 days.)
*/
NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init];
[componentsToSubtract setDay: - ([weekdayComponents weekday] - )];
beginningOfWeek = nil;
beginningOfWeek = [calendar dateByAddingComponents:componentsToSubtract toDate:self options:];
[componentsToSubtract release]; //normalize to midnight, extract the year, month, and day components and create a new date from those components.
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit |NSDayCalendarUnit)
fromDate:beginningOfWeek];
return [calendar dateFromComponents:components];
}
//返回当前天的年月日.
- (NSDate *)beginningOfDay {
NSCalendar *calendar = [NSCalendar currentCalendar];
// Get the weekday component of the current date
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit |NSDayCalendarUnit)
fromDate:self];
return [calendar dateFromComponents:components];
}
//返回该月的第一天
- (NSDate *)beginningOfMonth
{
return [self dateAfterDay:-[self getDay] + ];
}
//该月的最后一天
- (NSDate *)endOfMonth
{
return [[[self beginningOfMonth] dateafterMonth:] dateAfterDay:-];
}
//返回当前周的周末
- (NSDate *)endOfWeek {
NSCalendar *calendar = [NSCalendar currentCalendar];
// Get the weekday component of the current date
NSDateComponents *weekdayComponents = [calendar components:NSWeekdayCalendarUnit fromDate:self];
NSDateComponents *componentsToAdd = [[NSDateComponents alloc] init];
// to get the end of week for a particular date, add (7 - weekday) days
[componentsToAdd setDay:( - [weekdayComponents weekday])];
NSDate *endOfWeek = [calendar dateByAddingComponents:componentsToAdd toDate:self options:];
[componentsToAdd release]; return endOfWeek;
} + (NSString *)dateFormatString {
return @"yyyy-MM-dd";
} + (NSString *)timeFormatString {
return @"HH:mm:ss";
} + (NSString *)timestampFormatString {
return @"yyyy-MM-dd HH:mm:ss";
} // preserving for compatibility
+ (NSString *)dbFormatString {
return [NSDate timestampFormatString];
}
@end

ios开发分类--NSDate+Helpers的更多相关文章

  1. iOS开发---分类和扩展(Categories和Extensions)

      1.分类能够做到的事情主要是:即使在你不知道一个类的源码情况下,向这个类添加扩展的方法.   此外,分类能够保证你的实现类和其他的文件区分开.   1 #import “UIViewControl ...

  2. iOS开发中NSDate时间戳的转换--

    NSTimeInterval time =(NSTimeInterval )[model.day floatValue]; NSDate *date = [NSDate dateWithTimeInt ...

  3. iOS开发系列-NSDate

    NSDate API 获取当前时间 获取时间戳 创建间隔指定时间戳的Date // 获取昨天 NSTimeInterval time = 24 * 60 * 60; NSDate *date = [N ...

  4. iOS开发时间戳与时间NSDate,时区的转换,汉字与UTF8,16进制的转换

    http://blog.sina.com.cn/s/blog_68661bd80101njdo.html 标签: ios时间戳 ios开发时间戳 ios16进制转中文 ios开发utf8转中文 ios ...

  5. iOS开发:创建真机调试证书 分类: ios相关 2015-04-10 10:22 149人阅读 评论(0) 收藏

    关于苹果iOS开发,笔者也是从小白过来的,经历过各种困难和坑,其中就有关于开发证书,生产证书,in_house证书,add_Hoc证书申请过程中的问题,以及上架发布问题.今天就着重说一下关于针对于苹果 ...

  6. iOS开发UITableView基本使用方法总结 分类: ios技术 2015-04-03 17:51 68人阅读 评论(0) 收藏

    本文为大家呈现了iOS开发中UITableView基本使用方法总结.首先,Controller需要实现两个delegate ,分别是UITableViewDelegate 和UITableViewDa ...

  7. iOS开发~CocoaPods使用详细说明 分类: ios相关 2015-04-01 16:45 68人阅读 评论(0) 收藏

    iOS开发-CocoaPods使用详细说明 一.概要 iOS开发时,项目中会引用许多第三方库,CocoaPods(https://github.com/CocoaPods/CocoaPods)可以用来 ...

  8. IOS 开发中要注意的事项

    1.关于拍摄 TGCameraViewController – 基于 AVFoundation 的自定义相机.样式漂亮,轻量并且可以很容易地集成到 iOS 项目中.不会内存吃紧 2.block 中对控 ...

  9. iOS开发系列--数据存取

    概览 在iOS开发中数据存储的方式可以归纳为两类:一类是存储为文件,另一类是存储到数据库.例如前面IOS开发系列-Objective-C之Foundation框架的文章中提到归档.plist文件存储, ...

随机推荐

  1. C++实现禁忌搜索解决TSP问题

    C++实现禁忌搜索解决TSP问题 使用的搜索方法是Tabu Search(禁忌搜索) 程序设计 1) 文件读入坐标点计算距离矩阵/读入距离矩阵 for(int i = 0; i < CityNu ...

  2. 二、secureCRT的 使用过程

    准备工作: win7与linux能互相ping通 linux安装了ssh被登陆服务 关闭window 防火墙,,控制面板 下载secureCRT 参考资料:http://zhidao.baidu.co ...

  3. WPF——数据绑定(一)什么是数据绑定

    注意:本人初学WPF,文中可能有表达或者技术性问题,欢迎指正!谢谢! 一:什么是数据绑定? “Windows Presentation Foundation (WPF) 数据绑定为应用程序提供了一种简 ...

  4. CS小分队第一阶段冲刺站立会议(5月7日)

    昨日完成任务:1.完成了游戏2048退出自动保存功能,进入自动读取存档功能, 2.完成游戏失败判断函数, 3.为游戏添加了背景音乐并且可以手动开关 遇到的困难:使用数据库时由于使用的ACCESS版本比 ...

  5. 【扩展】Canvas绘制列表的尝试

    传送:http://www.alloyteam.com/2015/10/canvas-attempts-to-draw-list/ 来自:on 2015年10月30日 by TAT.Cson view ...

  6. mysql 存储过程 -- 游标的使用(备忘)

    BEGIN ; DECLARE f_ratio FLOAT DEFAULT 0.8; ); ); DECLARE i_statDate DATE; DECLARE i_accumulateCount ...

  7. KMP算法原理

    前几天在看数据结构与算法,里面提到过kmp算法,一个超级经典的字符串匹配算法.虽然网上有一大堆关于kmp算法的介绍文章,但是我看过之后还是“不明觉厉”.所以打算自己写写,大家一起学习吧. 一.关于KM ...

  8. 重读《Struts In Action》

    Figure   1.1. The Java Servlet API exposes the HTTP client/server protocol to the Java   platform. S ...

  9. 在C#中创建word文档

    在下面文档中  首先引用word组件:Microsoft.Office.Interop.Word 在头文件中写上 using Word = Microsoft.Office.Interop.Word; ...

  10. 【POJ】【1635】Subway Tree Systems

    树的最小表示法 给定两个有根树的dfs序,问这两棵树是否同构 题解:http://blog.sina.com.cn/s/blog_a4c6b95201017tlz.html 题目要求判断两棵树是否是同 ...