将NSString转换为NSDate(并返回)

我如何将“ 01/02/10 ”(意思是2010年2月1日)的NSString转换成NSDate ? 我怎么能把NSDate变成一个string?

Swift 4和更高版本

更新date:2017年11月16日

string到date

 var dateString = "02-03-2017" var dateFormatter = DateFormatter() // This is important - we set our input date format to match our input string // if the format doesn't match you'll get nil from your string, so be careful dateFormatter.dateFormat = "dd-MM-yyyy" //`date(from:)` returns an optional so make sure you unwrap when using. var dateFromString: Date? = dateFormatter.date(from: dateString) 

date到string

 var formatter = DateFormatter() formatter.dateFormat = "dd-MM-yyyy" guard let unwrappedDate = dateFromString else { return } //Using the dateFromString variable from before. let stringDate: String = formatter.string(from: dateFromString) 

Swift 3

更新date:2017年7月20日

string到NSDate

 var dateString = "02-03-2017" var dateFormatter = DateFormatter() // This is important - we set our input date format to match our input string // if the format doesn't match you'll get nil from your string, so be careful dateFormatter.dateFormat = "dd-MM-yyyy" var dateFromString = dateFormatter.date(from: dateString) 

NSDate到string

 var formatter = DateFormatter() formatter.dateFormat = "dd-MM-yyyy" let stringDate: String = formatter.string(from: dateFromString) 

迅速

更新date:2015年10月22日

string到NSDate

 var dateString = "01-02-2010" var dateFormatter = NSDateFormatter() // this is imporant - we set our input date format to match our input string dateFormatter.dateFormat = "dd-MM-yyyy" // voila! var dateFromString = dateFormatter.dateFromString(dateString) 

NSDate到string

 var formatter = NSDateFormatter() formatter.dateFormat = "dd-MM-yyyy" let stringDate: String = formatter.stringFromDate(NSDate()) println(stringDate) 

Objective-C的

NSString到NSDate

 NSString *dateString = @"01-02-2010"; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"dd-MM-yyyy"]; NSDate *dateFromString = [dateFormatter dateFromString:dateString]; 

NSDate转换为NSString:

 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"dd-MM-yyyy"]; NSString *stringDate = [dateFormatter stringFromDate:[NSDate date]]; NSLog(@"%@", stringDate); 

为此做了一个NSString扩展

 // Simple as this. date = dateString.dateValue; 

感谢NSDataDetector ,它可以识别很多格式。

 '2014-01-16' dateValue is <2014-01-16 11:00:00 +0000> '2014.01.16' dateValue is <2014-01-16 11:00:00 +0000> '2014/01/16' dateValue is <2014-01-16 11:00:00 +0000> '2014 Jan 16' dateValue is <2014-01-16 11:00:00 +0000> '2014 Jan 16th' dateValue is <2014-01-16 11:00:00 +0000> '20140116' dateValue is <2014-01-16 11:00:00 +0000> '01-16-2014' dateValue is <2014-01-16 11:00:00 +0000> '01.16.2014' dateValue is <2014-01-16 11:00:00 +0000> '01/16/2014' dateValue is <2014-01-16 11:00:00 +0000> '16 January 2014' dateValue is <2014-01-16 11:00:00 +0000> '01-16-2014 17:05:05' dateValue is <2014-01-16 16:05:05 +0000> '01-16-2014 T 17:05:05 UTC' dateValue is <2014-01-16 17:05:05 +0000> '17:05, 1 January 2014 (UTC)' dateValue is <2014-01-01 16:05:00 +0000> 

作为eppz!套件的一部分 ,从GitHub获取NSString + EPPZKit.h类别。


原始答案:无论您不确定(或不关心)string中包含的date格式,请使用NSDataDetector来parsingdate

 //Role players. NSString *dateString = @"Wed, 03 Jul 2013 02:16:02 -0700"; __block NSDate *detectedDate; //Detect. NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingAllTypes error:nil]; [detector enumerateMatchesInString:dateString options:kNilOptions range:NSMakeRange(0, [dateString length]) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) { detectedDate = result.date; }]; 

使用固定格式date时,需要将date格式化程序区域设置为"en_US_POSIX"

采取从数据格式指南

如果您使用的是固定格式date,则应首先将date格式程序的语言环境设置为适合您固定格式的内容。 在大多数情况下,最好的语言环境是en_US_POSIX,这个语言环境专门devise用来产生美国英语结果, 而不pipe用户和系统偏好 。 en_US_POSIX在时间上也是不变的(如果美国在将来的某个时候改变它的格式化date,en_US将改变以反映新的行为,但是en_US_POSIX不会),并且在平台之间(en_US_POSIX在iPhone上的工作方式相同操作系统,就像在OS X上做的一样,就像在其他平台上一样)。

Swift 3或更高版本

 extension Formatter { static let customDate: DateFormatter = { let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") formatter.dateFormat = "dd/MM/yy" return formatter }() static let time: DateFormatter = { let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") formatter.dateFormat = "HH:mm" return formatter }() static let weekdayName: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "cccc" return formatter }() static let month: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "LLLL" return formatter }() } 

 extension Date { var customDate: String { return Formatter.customDate.string(from: self) } var customTime: String { return Formatter.time.string(from: self) } var weekdayName: String { return Formatter.weekdayName.string(from: self) } var monthName: String { return Formatter.month.string(from: self) } } extension String { var customDate: Date? { return Formatter.customDate.date(from: self) } } 

用法:

 // this will be displayed like this regardless of the user and system preferences Date().customTime // "16:50" Date().customDate // "06/05/17" // this will be displayed according to user and system preferences Date().weekdayName // "Saturday" Date().monthName // "May" 

parsing自定义date并将date转换回相同的string格式:

 let dateString = "01/02/10" if let date = dateString.customDate { print(date.customDate) // "01/02/10\n" print(date.monthName) // customDate } 

在这里,您可以根据需要使用所有元素进行自定义:

在这里输入图像说明

为什么不添加一个类别到NSString?

 // NSString+Date.h @interface NSString (Date) + (NSDate*)stringDateFromString:(NSString*)string; + (NSString*)stringDateFromDate:(NSDate*)date; @end // NSString+Date.m NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; [dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss ZZZ"]; NSDate *date = [dateFormatter dateFromString:stringDate ]; [dateFormatter release]; + (NSDateFormatter*)stringDateFormatter { static NSDateFormatter* formatter = nil; if (formatter == nil) { formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss ZZZ"]; } return formatter; } + (NSDate*)stringDateFromString:(NSString*)string { return [[NSString stringDateFormatter] dateFromString:string]; } + (NSString*)stringDateFromDate:(NSDate*)date { return [[NSString stringDateFormatter] stringFromDate:date]; } // Usage (#import "NSString+Date.h") or add in "YOUR PROJECT".pch file NSString* string = [NSString stringDateFromDate:[NSDate date]]; NSDate* date = [NSString stringDateFromString:string]; 

用“10”代表一年不好,因为它可以是1910年,1810年等。你可能应该用4位数。

如果你可以改变date到类似的东西

 yyyymmdd 

那么你可以使用:

 // 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]; 
 NSString *dateStr = @"Tue, 25 May 2010 12:53:58 +0000"; // Convert string to date object NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat:@"EE, d LLLL yyyy HH:mm:ss Z"]; NSDate *date = [dateFormat dateFromString:dateStr]; [dateFormat release]; 
 // Convert string to date NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat:@"yyyyMMdd"]; NSDate *date = [dateFormat dateFromString:dateStr]; // Convert Date to string [dateFormat setDateFormat:@"EEEE MMMM d, YYYY"]; dateStr = [dateFormat stringFromDate:date]; [dateFormat release]; 
 NSString *mystr=@"Your string date"; NSCalendar *cal = [NSCalendar currentCalendar]; NSDate *now = [dateFormatter dateFromString:mystr]; Nslog(@"%@",now); 

如果你想设置格式使用下面的代码:

 NSString *dateString = @"01-02-2010"; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; // this is important - we set our input date format to match our input string // if format doesn't match you'll get nil from your string, so be careful [dateFormatter setDateFormat:@"dd-MM-yyyy"]; NSDate *dateFromString = [[NSDate alloc] init]; // voila! dateFromString = [dateFormatter dateFromString:dateString]; Nslog(@"%@",[dateFormatter dateFromString:dateString]); 

使用此方法将NSString转换为NSdate

 -(NSDate *)getDateFromString:(NSString *)pstrDate { NSDateFormatter* myFormatter = [[NSDateFormatter alloc] init]; [myFormatter setDateFormat:@"dd/MM/yyyy"]; NSDate* myDate = [myFormatter dateFromString:pstrDate]; return myDate; } 

如果有人有兴趣在Swift这样的事情上做这样的事情,我有一个开始的东西,虽然这不是完美的。

 func detectDate(dateString: NSString) -> NSDate { var error: NSError? let detector: NSDataDetector = NSDataDetector.dataDetectorWithTypes(NSTextCheckingType.Date.toRaw(), error: &error)! if error == nil { var matches = detector.matchesInString(dateString, options: nil, range: NSMakeRange(0, dateString.length)) let currentLocale = NSLocale.currentLocale() for match in matches { match.resultType == NSTextCheckingType.Date NSLog("Date: \(match.date.description)") return match.date } } return NSDate() } 

你可以使用扩展名。

 extension NSDate { //NSString to NSDate convenience init(dateString:String) { let nsDateFormatter = NSDateFormatter() nsDateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss" // Add the locale if required here let dateObj = nsDateFormatter.dateFromString(dateString) self.init(timeInterval:0, sinceDate:dateObj!) } //NSDate to time string func getTime() -> String { let timeFormatter = NSDateFormatter() timeFormatter.dateFormat = "hh:mm" //Can also set the default styles for date or time using .timeStyle or .dateStyle return timeFormatter.stringFromDate(self) } //NSDate to date string func getDate() -> String { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "dd, MMM" return dateFormatter.stringFromDate(self) } //NSDate to String func getString() -> String { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss" return dateFormatter.stringFromDate(self) } } 

所以虽然执行实际代码将如下所示

  var dateObjFromString = NSDate(dateString: cutDateTime) var dateString = dateObjFromString.getDate() var timeString = dateObjFromString.getTime() var stringFromDate = dateObjFromString.getString() 

还有一些默认的方法,但我想它可能不适用于你从文档给出的格式

  -dateFromString(_:) -stringFromDate(_:) -localizedStringFromDate(_ date: NSDate, dateStyle dateStyle: NSDateFormatterStyle, timeStyle timeStyle: NSDateFormatterStyle) -> String 

date到NSString

 NSString *dateString = [NSString stringWithFormat:@"%@",[NSDate date]]; NSLog(@"string: %@",dateString ); //2015-03-24 12:28:49 +0000 

NSString到NSDate

 NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"]; NSDate *date = [formatter dateFromString:dateString]; NSLog(@"date: %@", date); //015-03-24 12:28:49 +0000 

最好的做法是build立自己的一般类,在那里你把所有的一般使用方法,在几乎所有的项目中有用的方法,并添加由@Pavanbuild议的代码为:

 + (NSDate *)getDateOutOfString:(NSString *)passedString andDateFormat:(NSString *)dateFormat{ NSString *dateString = passedString; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:dateFormat]; NSDate *dateFromString = [[NSDate alloc] init]; dateFromString = [dateFormatter dateFromString:dateString]; return dateFromString; } 

..等所有其他有用的方法

通过这样做,你开始为你的应用程序构build一个干净的可重用的代码。 干杯!

根据Swift 2.2

您可以轻松地从NSDate的string和string中获取NSDate。 例如

首先设置date格式化程序

 let formatter = NSDateFormatter(); formatter.dateStyle = NSDateFormatterStyle.MediumStyle formatter.timeStyle = .NoStyle formatter.dateFormat = "MM/dd/yyyy" 

现在从string获取date,反之亦然。

 let strDate = formatter.stringFromDate(NSDate()) print(strDate) let dateFromStr = formatter.dateFromString(strDate) print(dateFromStr) 

现在享受。

NSString到NSDate或NSDate到NSString

 //This method is used to get NSDate from string //Pass the date formate ex-"dd-MM-yyyy hh:mm a" + (NSDate*)getDateFromString:(NSString *)dateString withFormate:(NSString *)formate { // Converted date from date string NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]]; [dateFormatter setDateFormat:formate]; NSDate *convertedDate = [dateFormatter dateFromString:dateString]; return convertedDate; } //This method is used to get the NSString for NSDate //Pass the date formate ex-"dd-MM-yyyy hh:mm a" + (NSString *)getDateStringFromDate:(NSDate *)date withFormate:(NSString *)formate { // Converted date from date string NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; //[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]]; [dateFormatter setDateFormat:formate]; NSString *convertedDate = [dateFormatter stringFromDate:date]; return convertedDate; } 

上面的例子不是简单的为Swift 3.0+编写的

更新 – Swift 3.0+ – 将date转换为string

 let date = Date() // insert your date data here var dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" // add custom format if you'd like var dateString = dateFormatter.string(from: date)