ios开发分类--NSDate+Helpers

时间:2022-09-07 08:09:20
#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&comma;16进制的转换

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

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

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

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

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

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

    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. FineUI(开源版)v4&period;2&period;2发布(8年125个版本,官网示例突破300个)!

    开源版是 FineUI 的基石,从 2008 年至今已经持续发布了 120 多个版本,拥有会员 15,000 多位,捐赠会员达到 1,200 多位.   FineUI(开源版)v4.2.2 是 8 年 ...

  2. NOI2018准备Day1

    今天刷基础题,字符串实在不想刷,做了20到多维数组题.老师说要10分钟一道,然而我加上整理差不多半小时一道吧... 总感觉自己效率比别人低了好多好多好多倍. 基础不牢,地动山摇,最近还是好好稳固基础题 ...

  3. java之jar命令详解

    1. JAR 文件包 JAR 文件就是 Java Archive File,顾名思意,它的应用是与 Java 息息相关的,是 Java 的一种文档格式.JAR 文件非常类似 ZIP 文件——准确的说, ...

  4. 【hbase】使用thrift with python 访问HBase

    HBase 版本: 0.98.6 thrift   版本: 0.9.0 使用 thrift client with python 连接 HBase 报错: Traceback (most recent ...

  5. 开源项目Material Calendar View 学习记录 &lpar;一&rpar;

    开源项目Material Calendar View 学习记录 Github: https://github.com/prolificinteractive/material-calendarview ...

  6. 【QAQ的Minecraft】

    树套树被QAQ用木斧挖了,只剩二维RMQ了. 题目:      QAQ最近爱上了一款很平凡的游戏,叫做<Minecraft>.目前游戏更新到了1.12版本,他发现了一条新的指令:/fill ...

  7. mysql优化二之锁机制

    mysql优化二之锁机制 mysql提供了锁机制和MVCC机制来保证并发操作的安全性,这里主要讨论锁机制, MVCC见下篇文章 mysql的锁按照锁粒度可分为行锁与表锁,按照操作类型划分可读锁和写锁 ...

  8. mysql5&period;7设置简单密码报错ERROR 1819 &lpar;HY000&rpar;&colon; Your password does not satisfy the current policy requirements

    注:本文来源于<  mysql5.7设置简单密码报错ERROR 1819 (HY000): Your password does not satisfy the current policy r ...

  9. RewriteCond和13个mod&lowbar;rewrite应用举例Apache伪静态

    1.给子域名加www标记 RewriteCond %{HTTP_HOST} ^([a-z.]+)?example\.com$ [NC] RewriteCond %{HTTP_HOST} !^www\. ...

  10. 第2章 2&period;n物理层--数据通信基础知识总结

    数据通信基础知识总结