【发布时间】:2012-12-20 07:22:44
【问题描述】:
UIDatePickerModeDateAndTime 以格式返回输出
2012-12-20 07:15:18 +0000.
如何从输出中删除+0000?
我想截图,但我的名声不够,我希望它能解决我的问题。
【问题讨论】:
标签: ios datepicker format
UIDatePickerModeDateAndTime 以格式返回输出
2012-12-20 07:15:18 +0000.
如何从输出中删除+0000?
我想截图,但我的名声不够,我希望它能解决我的问题。
【问题讨论】:
标签: ios datepicker format
- (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:。
【讨论】:
对此有很多解决方案。其中一些是:
1) 用空字符串替换 + 0000
2) 将输出切片直到 (length - 5)
开发更多解决方案需要创造力。
【讨论】:
这样使用:
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
【讨论】:
这里是代码
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
【讨论】: