【问题标题】:How to parse datetime in Objective C [duplicate]如何在Objective C中解析日期时间[重复]
【发布时间】:2015-09-08 05:48:39
【问题描述】:

我的输入日期格式如下,如何使用 Objective C 解析它?

"created_at":"2015-09-03T12:56:37.922Z"
"created_at":"2015-09-04T07:08:20.349Z"
"created_at":"2015-09-03T09:22:33.058Z"

【问题讨论】:

  • 无法理解您的问题。请进一步解释。请展示你做了什么。
  • 我在 Json 服务器中有 tis 日期时间格式..想知道如何在我的 APP 中转换和解析
  • NSDateFormatter 就是为此而生的。
  • 您可以使用NSString *created_at = yourDictionary[@"created_at"] 获取此信息。如果您想将其转换为日期,请参考 (stackoverflow.com/questions/20993049/…) 并使用日期格式 @"yyyy-MM-dd'T'HH:mm:ss.SSSZ"
  • 赶上我的减号。可以用谷歌搜索大量类似的问题。 NSDateFormatter 将帮助您获取 NSDate 对象。

标签: ios objective-c iphone


【解决方案1】:

试试这个

NSString *getDate=@"2015-09-03T12:56:37.922Z";

NSDateFormatter* dateformat = [[NSDateFormatter alloc]init];
[dateformat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];

// convert NSstring to NSDate
NSDate* date = [dateformat dateFromString: getDate];
NSLog(@"date: %@",date);

// convert NSDate to NSString
NSString *newString = [dateformat stringFromDate:date];
NSLog(@"newString: %@", newString);

[dateformat setDateFormat:@"yyyy-MM-dd HH:mm a"];

   // convert NSDate to NSString
NSString *finalString = [dateformat stringFromDate:date];
NSLog(@"final String: %@", finalString);  

【讨论】:

  • 例如我在这里添加的目的....
  • 是的,谢谢你,但我想要和 2015-09-03 12.56(上午或下午)完全一样。像这样
  • 好的,等我修改我的答案
  • 谢谢你得到了我所期望的那个
  • 如果我的答案很好,请为答案投票,这对未来很有用
【解决方案2】:

您的日期 =“2015-09-03T12:56:37.922Z”

let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSX"
var parsedDateString = formatter.stringFromDate(date)

【讨论】:

  • 这很快。您在下面有 ObjC,由 Anbu.Karthik 先生提供
  • 为什么投反对票,如果有人想在 swift 上工作,那是有希望的
【解决方案3】:

使用日期格式化程序将字符串转换为 NSDate 对象。并在格式化程序中为自定义文本使用单引号。

NSString *dateString = @"2015-09-03T12:56:37.922Z";
NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
NSDate *myDate = [dateFormatter dateFromString:dateString];

您可以使用另一个格式化程序来获取所需格式的日期

NSDateFormatter *anotherDateFormatter = [NSDateFormatter new];
[anotherDateFormatter setDateFormat: @"yyyy-MM-dd";
[anotherDateFormatter stringFromDate: myDate];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-11
    • 1970-01-01
    • 1970-01-01
    • 2020-06-26
    • 1970-01-01
    相关资源
    最近更新 更多