我在格式化程序的帮助下将此日期字符串"05/20/2015 05:27 pm"
转换为NSDate
,但它返回nil
。
-(NSDate *)dateFromString:(NSString *)strDate withFormat:(NSString *)strDateFormat
{
NSDate *date = nil;
[self.dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
if (strDate) {
if (strDateFormat) {
[self.dateFormatter setDateFormat:strDateFormat];
}
date = [self.dateFormatter dateFromString:strDate];
}
return date;
}
我正在使用上面的函数,我将字符串"05/20/2015 05:27 pm"
传递给格式@"dd/MM/yyyy HH:mm:ss"
。
答案 0 :(得分:1)
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"mm/dd/yyyy hh:mm a"];
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
NSDate *stringDate = [dateFormatter dateFromString:@"05/20/2015 05:27 pm"];
NSLog(@"%@", stringDate);
答案 1 :(得分:1)
-(NSDate *)dateFromString:(NSString *)strDate withFormat:(NSString *)strDateFormat
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:strDateFormat];
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
NSDate *date = [dateFormatter dateFromString:strDate];
return date;
}
答案 2 :(得分:0)
NSString *dateStr = @"05/20/2015 05:27 pm";
// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"dd-MM-yyyy HH:mm:ss Z"];
NSDate *date = [dateFormat dateFromString:dateStr];
Nslog(@"%@",date);
答案 3 :(得分:0)
要从NSDate转换为时间戳,您可以使用:
NSDate *date = [NSDate date];
NSTimeInterval timestampSeconds = [date timeIntervalSince1970];
结果将在几秒钟内完成。要将时间戳转换为标准毫秒,只需乘以1000
。
答案 4 :(得分:0)
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"mm/dd/yyyy hh:mm a"];
NSDate *strDate = [formatter dateFromString:@"05/20/2015 05:27 pm"];
NSLog(@"%@", strDate);//NSDate
time_t timeStamp = (time_t) [strDate timeIntervalSince1970];
NSLog(@"%ld", timeStamp);//timestamp
How to convert NSDate into unix timestamp iphone sdk?
这可能对您有所帮助:)。