#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. Python实现nb(朴素贝叶斯)

    Python实现nb(朴素贝叶斯) 运行环境 Pyhton3 numpy科学计算模块 计算过程 st=>start: 开始 op1=>operation: 读入数据 op2=>ope ...

  2. C#的winform矩阵简单运算

    C#的winform矩阵简单运算 程序截图 关键代码 using System; using System.Collections.Generic; using System.ComponentMod ...

  3. .gitignore无效,不能过滤某些文件

    利用.gitignore过滤文件,如编译过程中的中间文件,等等,这些文件不需要被追踪管理. 现象: 在.gitignore添加file1文件,以过滤该文件,但是通过git status查看仍显示fil ...

  4. 在数据表中添加一个字段的SQL语句怎么写

    如果要在数据表中添加一个字段,应该如何表示呢?下面就为您介绍表添加字段的SQL语句的写法,希望可以让您对SQL语句有更深的认识.   通用式: alter table [表名] add [字段名] 字 ...

  5. 搭建SpringMVC+MyBatis开发框架三

    新增spingmvc.xml配置 在WEB-INF下新增spingmvc.xml,主要是配置spring扫描的包:  <?xml version="1.0" encodin ...

  6. Matlab稀疏矩阵

    一.矩阵存储方式 MATLAB的矩阵有两种存储方式,完全存储方式和稀疏存储方式 1.完全存储方式 将矩阵的全部元素按列存储,矩阵中的全部零元素也存储到矩阵中. 2.稀疏存储方式 仅存储矩阵所有的非零元 ...

  7. sqlite时间比较语法

    如下: 字段 > datetime('2000-01-01 01:01:01') AND 字段 < datetime('2001-01-01 01:01:01');

  8. 8大排序算法图文讲解 分类: Brush Mode 2014-08-18 11:49 78人阅读 评论(0) 收藏

    排序算法可以分为内部排序和外部排序,内部排序是数据记录在内存中进行排序,而外部排序是因排序的数据很大,一次不能容纳全部的排序记录,在排序过程中需要访问外存. 常见的内部排序算法有:插入排序.希尔排序. ...

  9. EXCEL 跨表比较数据

    Public Sub Compare(fullname As String, sheet As String) Dim conn, sql, rows, i, cellContents ,rowInd ...

  10. BLUR

    ssao的blur遇到个麻烦 花了两三天时间...终于大概知道原因了. 在nvidia的ssao(http://developer.download.nvidia.com/SDK/10.5/direc ...