我从服务器获取DateTime
字符串" 2016年8月27日上午6:56:23"
我想从此字符串中获取仅日期。
NSString *StreamStartDateTime=@"8/27/2016 6:56:23 AM";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyyMMdd"];
NSDate *date1=[dateFormatter dateFromString:StreamStartDateTime];
但问题是我在date1中变为null。
请帮我找出我做错的地方。
答案 0 :(得分:3)
您使用的是错误的dateFormat
。请用以下代码替换您的代码:
NSString *StreamStartDateTime=@"8/27/2016 6:56:23 AM";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];
NSDate *date1=[dateFormatter dateFromString:StreamStartDateTime];
答案 1 :(得分:2)
喜欢
NSString *StreamStartDateTime=@"8/27/2016 6:56:23 AM";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM/dd/yyyy h:mm:ss a"]; or use hh:mm:ss a
NSDate *date1=[dateFormatter dateFromString:StreamStartDateTime];
[dateFormatter setDateFormat:@"yyyyMMdd"];
NSString *ssecond=[dateFormatter stringFromDate:date1];
NSDate *finalDate=[dateFormatter dateFromString:ssecond];
最终输出为
答案 2 :(得分:0)
您的日期格式必须与日期字符串匹配。
因此,如果您的日期字符串为8/27/2016 6:56:23 AM
,那么您的格式必须为MM/dd/yyyy hh:mm:ss a
。然后使用此格式从字符串获取日期,如
NSDate *date=[df dateFromString:StreamStartDateTime];
现在,以您想要日期的任何格式更改日期格式化程序,
[df setDateFormat:@"yyyyMMdd"];
然后
NSString *resultDateStr = [df stringFromDate:date];
答案 3 :(得分:0)
可以尝试这样
NSString *StreamStartDateTime=@"8/27/2016 6:56:23 AM";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MM/dd/yyyy h:mm:ss a"];
NSDate *streamStartDate = [formatter dateFromString:StreamStartDateTime];
[formatter setDateFormat:@"yyyyMMdd"];
NSString *strDate = [formatter stringFromDate:streamStartDate];
NSDate *compDate = [formatter dateFromString:strDate]; // Get date in UTC format
输出:
打印strDate的说明: 20160827
打印compDate的说明: 2016-08-26 18:30:00 +0000
答案 4 :(得分:0)
NSString *LiveStreamStartDateTime=@"8/27/2016 6:56:23 AM";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM/dd/yyyy h:mm:ss a"];
NSDate *date1=[dateFormatter dateFromString:LiveStreamStartDateTime];
[dateFormatter setDateFormat:@"MM/dd/yyyy"];
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
NSString *fisrtdate=[dateFormatter stringFromDate:date1];
NSDate *date11 = [dateFormatter dateFromString:fisrtdate];