【问题标题】:What is the best way to separate date and time from a nsstring将日期和时间与 nsstring 分开的最佳方法是什么
【发布时间】:2013-01-08 08:39:32
【问题描述】:

我有一个NSStirng,其中包含2013-01-08 07:52:00 +0000。我想用不同的NSStrings分隔日期和时间。

感谢任何帮助。

【问题讨论】:

标签: objective-c ios cocoa-touch


【解决方案1】:

来自服务器的格式是否一致?

您是否需要将日期和时间用于排序等...或添加时间或只是显示它们?

如果您只是显示它们并且字符串的格式不会改变,那么您可以这样做...

//assumption 1: the format is <date>space<time>space<timezone>
//assumption 2: the only purpose is to display the values sent from the server.

NSString *dateString = @"2013-01-08 07:52:00 +0000";
NSArray *components = [dateString componentsSeparatedByString:@" "];
NSString *date = components[0];
NSString *time = components[1];

【讨论】:

  • 谢谢,我的只有在服务器的格式适合显示时才是正确的。使用您的,您可以更改月份、时间等的显示格式... :-)
  • 是的..但是对于不需要任何交替的人来说,这很适合
  • 看..他接受了!意思是,他不想要任何灵活性!!好答案
【解决方案2】:

首先要做的是将你的日期字符串转换成NSDate

NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss Z"];
NSDate * date = [formatter dateFromString: @"2013-01-08 07:52:00 +0000"];

然后您可以使用格式化程序再次反转该过程并返回日期和时间。您可以根据需要调整每个的格式。

[formatter setTimeStyle:NSDateFormatterShortStyle];  // Get the time only
[formatter setDateStyle:NSDateFormatterNone];
NSString * timeString = [formatter stringFromDate: date];

[formatter setTimeStyle:NSDateFormatterNone];
[formatter setDateStyle:NSDateFormatterShortStyle];  // Get the date only
NSString * dateString = [formatter stringFromDate: date];

【讨论】:

    【解决方案3】:

    试试下面的代码,

        NSString *maindateString = @"2013-01-08 07:52:00 +0000";
        NSDateFormatter *myFormat = [[NSDateFormatter alloc] init];
        [myFormat setDateFormat:@"yyyy-mm-dd hh:mm:ss Z"];
        NSDate *mainDateDate = [myFormat dateFromString:maindateString];
        [myFormat setDateFormat:@"yyyy-mm-dd"];
        NSString *stringDate = [myFormat stringFromDate:mainDateDate];
    

    检查NSString stringDate 有你需要的:-)

    编辑:要获取时间字符串,请添加以下代码:

        NSDateFormatter *myFormat2 = [[NSDateFormatter alloc] init];
        [myFormat2 setDateFormat:@"HH:mm:ss"];
        NSString *stringTime = [myFormat2 stringFromDate:mainDateDate];
        NSLog(@"%@",stringTime);
    

    问候

    【讨论】:

    • 两件事:您的答案中的月份格式不正确,您为什么要从日期减去 5.5 小时才能得到 GMT?
    • @AshleyMills 嗨,如果我不减去时间间隔,时间会提前 5.30,这是我们在印度的时区,与 GMT 相比
    【解决方案4】:

    请根据该字符串创建一个日期:

    NSString to NSDate

    然后使用这些(或将它们转换回字符串)。这样就省了。

    无论如何,您应该在 NSString 之前有一个 NSDate - 是吗?为什么不保留那个?

    【讨论】:

    • 从服务器获取字符串。
    猜你喜欢
    • 2011-06-05
    • 1970-01-01
    • 2018-04-11
    • 1970-01-01
    • 2020-09-16
    • 2016-12-16
    • 2010-12-02
    • 2021-06-06
    • 1970-01-01
    相关资源
    最近更新 更多