#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. 有关ZxMiddleTier构想

    终于决定动手写一个自己的东西,没有其它想法,人已经30多了,感觉原来学的东西都是零散的,想通过这样一个中间层的项目,串联起原来所学的东西,形成一个体系,也算是对自己这么多年的程序员的生涯做出一个交代, ...

  2. OC学习心得【适合初学者】

    一.类和对象 1.OC语言是C语言的扩充,并且OC是iOS和OS X操作系统的编程语言. ①具备完善的面向对象特性: 封装:将现实世界中存在的某个客体的属性与行为绑定在一起,并放置在一个逻辑单元内 继 ...

  3. 【收藏】win7打开word每次提示配置解决办法

    打开“我的电脑”——“ C:\Program Files\Common Files\Microsoft Shared\OFFICE12\Office Setup Controller ”——找到一个“ ...

  4. C#制作高仿360安全卫士窗体(四)- 水晶按钮

    项目越来越紧,我也乐此不疲.自从上次C#制作高仿360安全卫士窗体(三)出来之后,就开始有一些人在说为什么还在坚持写这么落后的东西.我想说的是,我是从事企业信息化工作的,所有程序都只对内部使用.所以只 ...

  5. android开发 实现同时显示png/jpg 等bitmap图片还可以显示gif图片,有效防止OOM

    本来使用第三方jar包 GifView.jar  发现使用的时候不能显示png图片,而且多次setgifimage的时候还会OOM: 现在使用了一个新的第三方,demo是别人的, 下载链接:http: ...

  6. Analyzer使用第二Y轴,以及同一分析图不同量值使用不同的图形样式

    Analyzer的建立分析图后,图中有两个量值,希望能显示成不同的图形样式,如一个是柱图.一个是线图. 1.设置显示多个量值: 3.设置显示出图例,即表明图中量值内容的说明: 2.右键图例中要修改为不 ...

  7. 运用.NIT将数据存入数据库、读取数据库(运用封装)陈老师作业

    我基础不好,根据所学的知识,书本的例题修改的,也不知道我理解的是否符合老师要求 运用C#将数据存入数据库.并且可以读取数据库里的数据,此项目我运用了封装.我运用了一个窗体将数据存读数据. 我首先创建了 ...

  8. shiro中unauthorizedUrl不起作用

    解决方法: 在shiro配置文件中添加(异常全路径做key,错误页面做value) <bean class="org.springframework.web.servlet.handl ...

  9. Fiddler 过滤 css,图片等请求url 正则表达式

    设置步骤: 1.勾选 Request Headers 中的 Hide if url contains 过滤项 2.贴入下方正则表达式 REGEX:(?insx)/[^?/]*.(css|ico|jpg ...

  10. Uart串口与RS232串口的区别

    Uart指的是TTL电平的串口:RS232指的是RS232电平的串口. TTL电平是3.3V的,而RS232是负逻辑电平,它定义+5~+12V为低电平,而-12~-5V为高电平. Uart串口的RXD ...