iOS中date和string的转换

代码产自MKNetworkKit中的NSDate+RFC1123

分类中总共两个方法,分别是

+ (NSDate *)dateFromRFC1123:(NSString *)value_;//将字符串转为时间类型

- (NSString *)rfc1123String;//将时间类型转为字符串

这里面有个RCF1123时间格式的字符串作为转换前提。头文件有时间相关的time.h和调整程序位置的xlocale。

一:+ (NSDate *)dateFromRFC1123:(NSString *)value_;

  虽然方法名字和对应的翻译说的都是rfc1123time,但源码中的实现,对时间的格式分为rfc1123timeinfo、rfc850timeinfo、asctimeinfo三种时间格式。且为顺序,如果单看方法名字,呵呵...

  个人猜测,后面两种是对输入字符串字面量的扩展,如输入的是后两种,同样有非nil返回。

  对这三种实在没什么研究,权当作者顺序的意图就是优先级排序了

  对于设计思路就是简单的按照所给的格式->格式化后返回。

  出示代码前,先熟悉几个time的函数和结构体

  1、struct tm表示时间的结构体。 time_t一个长整型的typedef 

  2、void *memset(void *, int, size_t);//这里分别用$0、$1、$2表示前面的三个参数。此函数的功能为,将$0的前$2个字节赋值为$1

  3、char *strptime_l(const char * __restrict, const char * __restrict, struct tm * __restrict, locale_t)//将$0按照$1的格式解析,并赋值给$2,这里没有$3的什么事,直接赋值NULL。

  4、time_t mktime(struct tm *) __DARWIN_ALIAS(mktime); 也就是time_t mktime(struct tm *)//时间转换为自1970年1月1日以来持续时间的秒数

  以上差不多就是C/C++相关的

    对于输入非空判断略过不提

   const char *str = [value_ UTF8String]; 

      const char *fmt;

      NSDate *retDate;

      char *ret;

  先看rfc1123timeinfo的

  fmt = "%a, %d %b %Y %H:%M:%S %Z";

      struct tm rfc1123timeinfo;

      memset(&rfc1123timeinfo, 0, sizeof(rfc1123timeinfo));

      ret = strptime_l(str, fmt, &rfc1123timeinfo, NULL);

      if (ret) {

          time_t rfc1123time = mktime(&rfc1123timeinfo);

          retDate = [NSDate dateWithTimeIntervalSince1970:rfc1123time];

          if (retDate != nil)

              return retDate;

      }

  然后rfc850timeinfo

  fmt = "%A, %d-%b-%y %H:%M:%S %Z";

     struct tm rfc850timeinfo;

     memset(&rfc850timeinfo, 0, sizeof(rfc850timeinfo));

     ret = strptime_l(str, fmt, &rfc850timeinfo, NULL);

     if (ret) {

         time_t rfc850time = mktime(&rfc850timeinfo);

         retDate = [NSDate dateWithTimeIntervalSince1970:rfc850time];

         if (retDate != nil)

             return retDate;

     }

   最后是asctimeinfo

  fmt = "%a %b %e %H:%M:%S %Y";

  其他代码如上,同一个模版格式。

  最后添加返回nil的代码。OVER!

二、 -(NSString*)rfc1123String

  1、struct tm *gmtime_r(const time_t * __restrict, struct tm * __restrict);//日历时间转换为用UTC时间表示的时间,并将数据存储到提供的结构体中,返回结构体

  2、size_t strftime_l(char * __restrict, size_t, const char * __restrict, const struct tm * __restrict, locale_t)//将$4按照$3的格式保存到$0中。$1是$0的大小,最后一个无关,同样设置为NULL。并返回第二个参数。

  代码如下

  time_t date = (time_t)[self timeIntervalSince1970];

     struct tm timeinfo;

     gmtime_r(&date, &timeinfo);

     char buffer[32];

     size_t ret = strftime_l(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S GMT", &timeinfo, NULL);

     if (ret) {

         return @(buffer);

     } else {

         return nil;

     }

***********************************!!!完毕!!!*************************************

原文地址:https://www.cnblogs.com/liuguanlei/p/4933169.html