ios开发处理服务器返回的时间字符串
#import <Foundation/Foundation.h> void other();
void string2date(); int main(int argc, const char * argv[]) {
@autoreleasepool {
other(); string2date();
}
return ;
} void other()
{
// 获得NSCalendar
NSCalendar *calendar = nil;
if ([NSCalendar respondsToSelector:@selector(calendarWithIdentifier:)]) {
calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
} else {
calendar = [NSCalendar currentCalendar];
} NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss"; NSLog(@"%zd", [calendar isDateInToday:[fmt dateFromString:@"2015-11-10 01:09:56"]]); } void dateCompare3()
{
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss"; // 时间字符串
NSString *createdAtString = @"2015-11-01 09:10:05";
NSDate *createdAtDate = [fmt dateFromString:createdAtString]; // 其他时间
NSString *otherString = @"2015-10-31 08:56:45";
NSDate *otherDate = [fmt dateFromString:otherString]; // 获得NSCalendar
NSCalendar *calendar = nil; if ([NSCalendar respondsToSelector:@selector(calendarWithIdentifier:)]) {
calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
} else {
calendar = [NSCalendar currentCalendar];
} // 获得日期之间的间隔
NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
NSDateComponents *cmps = [calendar components:unit fromDate:createdAtDate toDate:otherDate options:]; NSLog(@"%@", cmps);
} void dateCompare2()
{
// 时间字符串
NSString *createdAtString = @"2015-11-20 09:10:05";
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSDate *createdAtDate = [fmt dateFromString:createdAtString]; // 手机当前时间
// NSDate *nowDate = [NSDate date]; // 获得createdAtDate和nowDate的时间间隔(间隔多少秒)
// NSTimeInterval interval = [nowDate timeIntervalSinceDate:createdAtDate];
NSTimeInterval interval = [createdAtDate timeIntervalSinceNow]; NSLog(@"%f", interval);
} void dateCompare()
{
// 时间字符串
NSString *createdAtString = @"2015-11-20 11:10:05";
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSDate *createdAtDate = [fmt dateFromString:createdAtString]; // 手机当前时间
NSDate *nowDate = [NSDate date]; /**
NSComparisonResult的取值
NSOrderedAscending = -1L, // 升序, 越往右边越大
NSOrderedSame, // 相等
NSOrderedDescending // 降序, 越往右边越小
*/
// 获得比较结果(谁大谁小)
NSComparisonResult result = [nowDate compare:createdAtDate];
if (result == NSOrderedAscending) { // 升序, 越往右边越大
NSLog(@"createdAtDate > nowDate");
} else if (result == NSOrderedDescending) { // 降序, 越往右边越小
NSLog(@"createdAtDate < nowDate");
} else {
NSLog(@"createdAtDate == nowDate");
}
} /**
* 日期元素 : 年月日时分秒
*/
void getComponentsOfDate3()
{
// 时间字符串
NSString *string = @"2015-11-20 09:10:05"; // 日期格式化类
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
// 设置日期格式(为了转换成功)
fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss"; // NSString * -> NSDate *
NSDate *date = [fmt dateFromString:string]; // 利用NSCalendar处理日期
NSCalendar *calendar = [NSCalendar currentCalendar]; NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
NSDateComponents *cmps = [calendar components:unit fromDate:date]; // NSLog(@"%zd %zd %zd", cmps.year, cmps.month, cmps.day);
NSLog(@"%@", cmps);
} /**
* 日期元素 : 年月日时分秒
*/
void getComponentsOfDate2()
{
// 时间字符串
NSString *string = @"2015-11-20 09:10:05"; // 日期格式化类
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
// 设置日期格式(为了转换成功)
fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss"; // NSString * -> NSDate *
NSDate *date = [fmt dateFromString:string]; // 利用NSCalendar处理日期
NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger month = [calendar component:NSCalendarUnitMonth fromDate:date];
NSInteger hour = [calendar component:NSCalendarUnitHour fromDate:date];
NSInteger minute = [calendar component:NSCalendarUnitMinute fromDate:date]; NSLog(@"%zd %zd %zd", month, hour, minute);
} /**
* 日期元素 : 年月日时分秒
*/
void getComponentsOfDate()
{
// 时间字符串
NSString *string = @"2015-11-20 09:10:05"; NSString *month = [string substringWithRange:NSMakeRange(, )]; NSLog(@"%@", month);
} void date2string()
{
NSDate *date = [NSDate date]; NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
fmt.dateFormat = @"yyyy年MM月dd号 HH:mm:ss"; NSString *string = [fmt stringFromDate:date]; NSLog(@"----%@+++++", string); } void string2date4()
{
// 时间戳 : 从1970年1月1号 00:00:00开始走过的毫秒数 // 时间字符串 - 时间戳
NSString *string = @""; NSTimeInterval second = string.longLongValue / 1000.0; // 时间戳 -> NSDate *
NSDate *date = [NSDate dateWithTimeIntervalSince1970:second]; NSLog(@"%@", date);
} void string2date3()
{
// 时间字符串
NSString *string = @"Tue May 31 17:46:55 +0800 2011"; // 日期格式化类
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
fmt.dateFormat = @"EEE MMM dd HH:mm:ss Z yyyy";
// fmt.dateFormat = @"EEE MMM dd HH:mm:ss ZZZZ yyyy";
// 设置语言区域(因为这种时间是欧美常用时间)
fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]; NSLog(@"%@", [fmt dateFromString:string]);
} void string2date2()
{
// 时间字符串
NSString *string = @"11月-20号/2015年 09-10:05秒"; // 日期格式化类
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
fmt.dateFormat = @"MM月-dd号/yyyy年 HH-mm:ss秒"; NSLog(@"%@", [fmt dateFromString:string]);
} void string2date()
{
// 时间字符串
NSString *string = @"2015-11-20 09:33:22"; // 日期格式化类
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
// 设置日期格式(为了转换成功)
fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss"; // NSString * -> NSDate *
NSDate *date = [fmt dateFromString:string]; NSString *newStr = [fmt stringFromDate:date]; NSLog(@"%@", date);
NSLog(@"%@", newStr); }
总结:
## NSDateFormatter的作用
- NSString \* -> NSDate *
```obj
- (nullable NSDate *)dateFromString:(NSString *)string;
```
- NSDate \* -> NSString *
```objc
- (NSString *)stringFromDate:(NSDate *)date;
```
## 常见的日期格式
- http://www.cnblogs.com/mailingfeng/archive/2011/07/28/2120422.html
## NSString \* -> NSDate *
- 2015-11-20 09:10:05
```objc
// 时间字符串
NSString *string = @"2015-11-20 09:10:05";
// 日期格式化类
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
// 设置日期格式(为了转换成功)
fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
// NSString * -> NSDate *
NSDate *date = [fmt dateFromString:string];
NSLog(@"%@", date);
```
- 11月-20号/2015年 09-10:05秒
```objc
// 时间字符串
NSString *string = @"11月-20号/2015年 09-10:05秒";
// 日期格式化类
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
fmt.dateFormat = @"MM月-dd号/yyyy年 HH-mm:ss秒";
NSLog(@"%@", [fmt dateFromString:string]);
```
- Tue May 31 17:46:55 +0800 2011
```objc
// 时间字符串
NSString *string = @"Tue May 31 17:46:55 +0800 2011";
// 日期格式化类
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
fmt.dateFormat = @"EEE MMM dd HH:mm:ss Z yyyy";
// fmt.dateFormat = @"EEE MMM dd HH:mm:ss ZZZZ yyyy";
// 设置语言区域(因为这种时间是欧美常用时间)
fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
NSLog(@"%@", [fmt dateFromString:string]);
```
- 1745645645645
```objc
// 时间戳 : 从1970年1月1号 00:00:00开始走过的毫秒数
// 时间字符串 - 时间戳
NSString *string = @"1745645645645";
NSTimeInterval second = string.longLongValue / 1000.0;
// 时间戳 -> NSDate *
NSDate *date = [NSDate dateWithTimeIntervalSince1970:second];
NSLog(@"%@", date);
```
## NSCalendar的注意点
```objc
#define iOS(version) ([UIDevice currentDevice].systemVersion.doubleValue >= (version))
NSCalendar *calendar = nil;
if ([UIDevice currentDevice].systemVersion.doubleValue >= 8.0) {
calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
} else {
calendar = [NSCalendar currentCalendar];
}
NSCalendar *calendar = nil;
if ([NSCalendar respondsToSelector:@selector(calendarWithIdentifier:)]) {
calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
} else {
calendar = [NSCalendar currentCalendar];
}
```
## NSDate \* -> NSString *
```objc
NSDate *date = [NSDate date];
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
fmt.dateFormat = @"yyyy年MM月dd号 HH:mm:ss";
NSString *string = [fmt stringFromDate:date];
```
## 获得日期元素
```objc
NSString *string = @"2015-11-20 09:10:05";
NSString *month = [string substringWithRange:NSMakeRange(5, 2)];
NSLog(@"%@", month);
```
```objc
// 时间字符串
NSString *string = @"2015-11-20 09:10:05";
// 日期格式化类
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
// 设置日期格式(为了转换成功)
fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
// NSString * -> NSDate *
NSDate *date = [fmt dateFromString:string];
// 利用NSCalendar处理日期
NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger month = [calendar component:NSCalendarUnitMonth fromDate:date];
NSInteger hour = [calendar component:NSCalendarUnitHour fromDate:date];
NSInteger minute = [calendar component:NSCalendarUnitMinute fromDate:date];
NSLog(@"%zd %zd %zd", month, hour, minute);
```
```objc
// 时间字符串
NSString *string = @"2015-11-20 09:10:05";
// 日期格式化类
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
// 设置日期格式(为了转换成功)
fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
// NSString * -> NSDate *
NSDate *date = [fmt dateFromString:string];
// 利用NSCalendar处理日期
NSCalendar *calendar = [NSCalendar currentCalendar];
NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
NSDateComponents *cmps = [calendar components:unit fromDate:date];
// NSLog(@"%zd %zd %zd", cmps.year, cmps.month, cmps.day);
NSLog(@"%@", cmps);
```
## 日期比较
```objc
// 时间字符串
NSString *createdAtString = @"2015-11-20 11:10:05";
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSDate *createdAtDate = [fmt dateFromString:createdAtString];
// 手机当前时间
NSDate *nowDate = [NSDate date];
/**
NSComparisonResult的取值
NSOrderedAscending = -1L, // 升序, 越往右边越大
NSOrderedSame, // 相等
NSOrderedDescending // 降序, 越往右边越小
*/
// 获得比较结果(谁大谁小)
NSComparisonResult result = [nowDate compare:createdAtDate];
if (result == NSOrderedAscending) { // 升序, 越往右边越大
NSLog(@"createdAtDate > nowDate");
} else if (result == NSOrderedDescending) { // 降序, 越往右边越小
NSLog(@"createdAtDate < nowDate");
} else {
NSLog(@"createdAtDate == nowDate");
}
```
```objc
// 时间字符串
NSString *createdAtString = @"2015-11-20 09:10:05";
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSDate *createdAtDate = [fmt dateFromString:createdAtString];
// 手机当前时间
// NSDate *nowDate = [NSDate date];
// 获得createdAtDate和nowDate的时间间隔(间隔多少秒)
// NSTimeInterval interval = [nowDate timeIntervalSinceDate:createdAtDate];
NSTimeInterval interval = [createdAtDate timeIntervalSinceNow];
NSLog(@"%f", interval);
```
```objc
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
// 时间字符串
NSString *createdAtString = @"2015-11-01 09:10:05";
NSDate *createdAtDate = [fmt dateFromString:createdAtString];
// 其他时间
NSString *otherString = @"2015-10-31 08:56:45";
NSDate *otherDate = [fmt dateFromString:otherString];
// 获得NSCalendar
NSCalendar *calendar = nil;
if ([NSCalendar respondsToSelector:@selector(calendarWithIdentifier:)]) {
calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
} else {
#import <Foundation/Foundation.h>
//typedef enum {
// /** 图片 */
// XMGTopicTypePicture = 10,
// /** 段子 */
// XMGTopicTypeWord = 29,
// /** 声音 */
// XMGTopicTypeVoice = 31,
// /** 视频 */
// XMGTopicTypeVideo = 41,
//} XMGTopicType;
typedef NS_ENUM(NSUInteger, XMGTopicType) {
/** 图片 */
XMGTopicTypePicture = ,
/** 段子 */
XMGTopicTypeWord = ,
/** 声音 */
XMGTopicTypeVoice = ,
/** 视频 */
XMGTopicTypeVideo =
};
@class XMGComment;
@interface XMGTopic : NSObject
/** 用户的名字 */
@property (nonatomic, copy) NSString *name;
/** 用户的头像 */
@property (nonatomic, copy) NSString *profile_image;
/** 帖子的文字内容 */
@property (nonatomic, copy) NSString *text;
/** 帖子审核通过的时间 */
@property (nonatomic, copy) NSString *created_at;
/** 顶数量 */
@property (nonatomic, assign) NSInteger ding;
/** 踩数量 */
@property (nonatomic, assign) NSInteger cai;
/** 转发\分享数量 */
@property (nonatomic, assign) NSInteger repost;
/** 评论数量 */
@property (nonatomic, assign) NSInteger comment;
/** 最热评论 */
@property (nonatomic, strong) XMGComment *top_cmt;
/** 帖子类型 */
@property (nonatomic, assign) XMGTopicType type;
@end
#import "XMGTopic.h" @implementation XMGTopic
#pragma mark - 其他
static NSDateFormatter *fmt_;
static NSCalendar *calendar_;
/**
* 在第一次使用XMGTopic类时调用1次
*/
+ (void)initialize
{
fmt_ = [[NSDateFormatter alloc] init];
calendar_ = [NSCalendar calendar];
} - (NSString *)created_at
{
// 获得发帖日期
fmt_.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSDate *createdAtDate = [fmt_ dateFromString:_created_at]; if (createdAtDate.isThisYear) { // 今年
if (createdAtDate.isToday) { // 今天
// 手机当前时间
NSDate *nowDate = [NSDate date];
NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
NSDateComponents *cmps = [calendar_ components:unit fromDate:createdAtDate toDate:nowDate options:]; if (cmps.hour >= ) { // 时间间隔 >= 1小时
return [NSString stringWithFormat:@"%zd小时前", cmps.hour];
} else if (cmps.minute >= ) { // 1小时 > 时间间隔 >= 1分钟
return [NSString stringWithFormat:@"%zd分钟前", cmps.minute];
} else { // 1分钟 > 分钟
return @"刚刚";
}
} else if (createdAtDate.isYesterday) { // 昨天
fmt_.dateFormat = @"昨天 HH:mm:ss";
return [fmt_ stringFromDate:createdAtDate];
} else { // 其他
fmt_.dateFormat = @"MM-dd HH:mm:ss";
return [fmt_ stringFromDate:createdAtDate];
}
} else { // 非今年
return _created_at;
}
} @end
calendar = [NSCalendar currentCalendar];
}
// 获得日期之间的间隔
NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
NSDateComponents *cmps = [calendar components:unit fromDate:createdAtDate toDate:otherDate options:0];
NSLog(@"%@", cmps);
```
例子:
ios开发处理服务器返回的时间字符串的更多相关文章
- iOS开发Swift篇—(三)字符串和数据类型
iOS开发Swift篇—(三)字符串和数据类型 一.字符串 字符串是String类型的数据,用双引号""包住文字内容 let website = "http://www ...
- iOS开发之动画中的时间(概况)
一.引言 在iOS开发中使用动画时,可以通过设置动画的duration.speed.begintime.offset属性,来设置动画的时长.速度.起始时间及起始偏移. 用一个简单的例子来说明各个参数的 ...
- 服务器返回的JSON字符串
异步请求将type设为"json",或者利 用$.getJSON()方法获得服务器返回,那么就不需要eval()方法,因为这时候得到的结果已经是json对象
- iOS开发之动画中的时间
概述 在动画中,我们会指定动画的持续时间.例如 scaleAnimation.duration = self.config.appearDuration 那么这个时间是怎么定义的呢?是指的绝对时间吗? ...
- IOS开发之——使用SBJson拼接Json字符串
SBJson包的下载地址在上一篇文章中. 能够使用NSDictionary中的键值对来拼接Json数据,很方便,也能够进行嵌套,直接上代码: //開始拼接Json字符串 NSDictionary *d ...
- iOS 开发 右滑返回上一级控制器
#import <objc/runtime.h> @interface UINavigationController (Transition)<UIGestureRecognizer ...
- iOS开发-NSDate获取当前时区时间
NSDate Date默认显示的是格林尼治所在地的标准时间(GMT),转换为中国时区需要加上八个小时,针对与这个情况你可以直接在获取时间之后加上八个小时,也可以转换到当前时区,都很简单,代码参考如下: ...
- ajax 获取服务器返回的XML字符串
前台 解析失败不会抛出任何异常, 只会返回一个给定的错误文档 let l = console.log let http = ajanuw.create({ uri: 'http://localhost ...
- 【ios开发】自定义Actionsheet实现时间选择器和省市区选择器
最近的工程有一个个人资料页面,需要填写生日和地区的信息,需要自己定义个actionsheet. 但是到网上搜了一下都不太合适,只好自己研究研究,重写了一个.共享出来给大家用用,突然发现自己精神很高尚吗 ...
随机推荐
- Day2二分图笔记
定义 左边一堆点 右边一堆点 树是一个二分图,奇数深度和偶数深度可以组成二分图, 二分图匹配 左边的点和右边的点有边 匈牙利算法 可能的答案 ans,n-ans,m-ans,n+m-ans || ...
- python路径找类并获取静态字段
Python通过路径找类并获取其中大写的静态字段 settings.py class Foo: DEBUG = True TEST = True xx.py import importlib path ...
- 解读OpenRTB(实时竞价)生态系统
最近3年,广告实时竞价(RealTimeBidding)模式逐渐流行起来. 2012年大致了解过,最近一段时间,重新温习下. 半壁江山 生态系统总的来说分为2个部分,卖方和买方. 卖方:媒体,即拥有广 ...
- 洛谷 P1130 红牌
P1130 红牌 题目描述 某地临时居民想获得长期居住权就必须申请拿到红牌.获得红牌的过程是相当复杂 ,一共包括N个步骤.每一步骤都由政府的某个工作人员负责检查你所提交的材料是否符合条件.为了加快进程 ...
- Objc执行时读取和写入plist文件遇到的问题
以下是本猫保持游戏NPC和物件交互的plist文件: 随着游戏和玩家逐步发生互动,玩家会改动人物和物件的交互的状态.这也是RPG游戏最主要的功能. 在切换每一个地图时须要将上一个地图发生的改变存储到p ...
- Delphi部份函数,命令,属性中文说明
Abort 函数 引起放弃的意外处理 Abs 函数 绝对值函数 AddExitProc 函数 将一过程添加到运行时库的结束过程表中 Addr 函数 返回指定对象的地址 AdjustLineBreaks ...
- 【MySQL集群】——Java程序连接MySQL集群
上篇简介了怎样在Windows环境下建立配置MySQL集群,这里用一个实现注冊功能的小Demo通过jdbc的方式连接到MySQL集群中. 外部程序想要远程连接到mysql集群,还须要做的一个操作就是设 ...
- HTML中input标签maxlength属性的妙处
HTML中的input标签可是很常用的. HTML本身也非常简单,就是若干标签,每个标签有若干属性. 我在学习HTML的过程中,也没有太过重视. 今年,在写前端表单验证的时候,发现maxlength这 ...
- Spring HandlerInterceptor的使用
http://blog.csdn.net/joeyon1985/article/details/49903761
- BZOJ——3343: 教主的魔法 || 洛谷—— P2801 教主的魔法
http://www.lydsy.com/JudgeOnline/problem.php?id=3343 || https://www.luogu.org/problem/show?pid=280 ...