将string转换为NSDate

如何将string转换为iOS上的NSDate

6 Solutions collect form web for “将string转换为NSDate”

 NSString *dateStr = @"20100223"; // Convert string to date object NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat:@"yyyyMMdd"]; NSDate *date = [dateFormat dateFromString:dateStr]; // Convert date object to desired output format [dateFormat setDateFormat:@"EEEE MMMM d, YYYY"]; dateStr = [dateFormat stringFromDate:date]; [dateFormat release]; 

希望这会帮助你。

你会想看看NSDateFormatter 。 确定datestring的格式,然后使用dateFromString:将string转换为NSDate对象。

 NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat:@"dd/MM/YYYY"]; NSDate *date = [dateFormat dateFromString:dateStr]; list = [self getYear:date]; - (NSMutableArray *)getYear:(NSDate*)date { NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:date]; int year = [components year]; int month = [components month]; int day = [components day]; NSLog(@"%d",year); NSMutableDictionary *dateDict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:@"%d", day], @"day", [NSString stringWithFormat:@"%d", month], @"month", [NSString stringWithFormat:@"%d", year], @"year", nil]; return dateDict; } 

一个简单的方法,即使你有sqlite数据库:

 // NSTimeInterval is basically typedef of double so you can receive it as double also. NSTimeInterval *current = [[NSDate date] timeIntervalSince1970]; [DB addToDB:current]; //retrieve the date from DB NSDate *retrievedDateItem = [[NSDate alloc] initWithTimeIntervalSince1970:[getDBValueAsDouble]]; //convert it from double (NSTimeInterval) to NSDate // Set the style [dateFormatter setDateStyle:NSDateFormatterMediumStyle]; [dateFormatter setTimeStyle:NSDateFormatterMediumStyle]; // Converted to string NSString *convertedDate = [dateFormatter stringFromDate:retrievedDateItem]; 

这个例子的输出:

2015年8月3日,12:27:50 PM

 +(NSDate*)str2date:(NSString*)dateStr{ if ([dateStr isKindOfClass:[NSDate class]]) { return (NSDate*)dateStr; } NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat:@"yyyy-MM-dd"]; NSDate *date = [dateFormat dateFromString:dateStr]; return date; } 

我在Swift中的工作版本

 func dateFor(timeStamp: String) -> NSDate { let formater = NSDateFormatter() formater.dateFormat = "HH:mm:ss:SSS - MMM dd, yyyy" return formater.dateFromString(timeStamp)! } func timeStampFor(date: NSDate) -> String { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "HH:mm:ss:SSS - MMM dd, yyyy" return dateFormatter.stringFromDate(date) } 
  • UIScrollView contentSize不起作用
  • 与ProgressView相结合的UISlider
  • cellForRowAtIndexPath如何工作?
  • 客户端/服务器GKSession
  • Objective-C中的方法重载?
  • 你如何实现全球iPhoneexception处理?
  • 对NSManagedObject属性值进行NSNull处理
  • 在委托属性声明中,'weak'和'assign'有什么区别
  • 优点,问题,添加另一个UIWindow到iOS应用程序的例子?
  • 在所有其他视图上添加UIView,包括StatusBar
  • 了解NSString比较