【问题标题】:UIDatePickerModeDateAndTime format 2012-12-20 07:15:18 +0000 without +0000UIDatePickerModeDateAndTime 格式 2012-12-20 07:15:18 +0000 没有 +0000
【发布时间】:2012-12-20 07:22:44
【问题描述】:

UIDatePickerModeDateAndTime 以格式返回输出

2012-12-20 07:15:18 +0000.

如何从输出中删除+0000

我想截图,但我的名声不够,我希望它能解决我的问题。

【问题讨论】:

    标签: ios datepicker format


    【解决方案1】:

    使用NSDateFormatter

    - (IBAction)dateChanged:(UIDatePicker *)sender {
        NSDate *date = sender.date;
        NSDateFormatter *df = [[NSDateFormatter alloc] init];
        [df setDateStyle:NSDateFormatterShortStyle];   // if you want to show the date to the user
        [df setTimeStyle:NSDateFormatterShortStyle];   // if you want to show the date to the user
        // [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];  // if you want to use the date for your model
    
        NSString *dateString = [df stringFromDate:date];
        NSLog(@"%@", dateString);
    }
    

    如果您想向用户显示日期,请使用setDateStyle:setTimeStyle:,因为它们可以识别区域设置并以正确的格式生成输出。 如果您只需要后端的日期(例如创建文件名),请使用setDateFormat:

    【讨论】:

      【解决方案2】:

      对此有很多解决方案。其中一些是:

      1) 用空字符串替换 + 0000

      2) 将输出切片直到 (length - 5)

      开发更多解决方案需要创造力。

      【讨论】:

        【解决方案3】:

        这样使用:

        NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyy-MM-dd HH:mm:ss"];
        NSDate *today = [NSDate date];
        NSString *dateString =[dateFormatter stringFromDate:today];
        NSLog(@"Date is: %@",dateString);
        

        输出:

        Date is: 2012-12-20 12:58:58
        

        【讨论】:

          【解决方案4】:

          这里是代码

          NSString *calDate = @"2011-11-11 21:56:38 +0000";
          
          NSDate *date = [[[NSDate alloc] init] retain];
          
          NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
          
          [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];  
          
          //                                   right here    ^
          
          date = [dateFormatter dateFromString:calDate];
          
          NSLog(@"date:%@", date);
          

          输出:

          2012-01-03 20:14:15.258 Craplet[38753:707] date:2011-11-11 21:56:38 +0000
          

          没有 Z:

          [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
          

          它输出:

          2012-01-03 20:16:10.456 Craplet[38885:707] date:(null)
          

          如果格式不能匹配到日期字符串,则返回nil

          【讨论】:

            猜你喜欢
            • 2022-07-26
            • 2014-02-03
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2023-03-26
            • 2022-08-07
            相关资源
            最近更新 更多