将NSString转换为NSDate(然后再次返回)


229

如何将NSString类似“ 01/02/10 ”(表示2010年2月1日)的内容转换为NSDate?我怎么能把NSDate琴弦变成绳子呢?


使用2010。然后看看我的帖子。我为这两个过程都提供了转换。
帕万

Answers:


450

Swift 4及更高版本

更新时间:2018年

字符串至今

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)

字符串日期

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)

迅捷3

更新时间:2017年7月20日

字符串到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转换为字符串

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

迅速

更新时间:2015年10月22日

字符串到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转换为字符串

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

物镜

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);

setDateFormat应该是两个y吗?
cannyboy

我不确定2年的工作。但是经验法则是您要给keeo设置setDateFormat相同格式的格式。所以在2010年的第一天,像这样“ yyyy”写4 y。我肯定一定会正常工作
Pavan

1
完全值得检查这篇文章。
iOmi

7
NSDate *dateFromString = [[NSDate alloc] init];如果在下一行中为指针分配新值,原因何在?
Valeriy Van

4
需要注意的另一项内容-如果您的字符串(日期)值列为2013年5月29日,则对setDateFormat的调用将需要匹配相同的内容-即[dateFormatter setDateFormat:@“ MM / dd / yyyy”]-我帮助的个人在字符串数据有斜杠时一直尝试使用连字符。-很好的答案,帕万。
noobzilla

54

更新2019(快速4):

为此进行了Date扩展。它使用NSDataDetector代替NSDateFormatter

// Just throw at it without any format.
var date: Date? = Date.FromString("02-14-2019 17:05:05")

非常令人愉快,它甚至可以识别“ Tomorrow at 5”之类的东西。

XCTAssertEqual(Date.FromString("2019-02-14"),                    Date.FromCalendar(2019, 2, 14))
XCTAssertEqual(Date.FromString("2019.02.14"),                    Date.FromCalendar(2019, 2, 14))
XCTAssertEqual(Date.FromString("2019/02/14"),                    Date.FromCalendar(2019, 2, 14))
XCTAssertEqual(Date.FromString("2019 Feb 14"),                   Date.FromCalendar(2019, 2, 14))
XCTAssertEqual(Date.FromString("2019 Feb 14th"),                 Date.FromCalendar(2019, 2, 14))
XCTAssertEqual(Date.FromString("20190214"),                      Date.FromCalendar(2019, 2, 14))
XCTAssertEqual(Date.FromString("02-14-2019"),                    Date.FromCalendar(2019, 2, 14))
XCTAssertEqual(Date.FromString("02.14.2019 5:00 PM"),            Date.FromCalendar(2019, 2, 14, 17))
XCTAssertEqual(Date.FromString("02/14/2019 17:00"),              Date.FromCalendar(2019, 2, 14, 17))
XCTAssertEqual(Date.FromString("14 February 2019 at 5 hour"),    Date.FromCalendar(2019, 2, 14, 17))
XCTAssertEqual(Date.FromString("02-14-2019 17:05:05"),           Date.FromCalendar(2019, 2, 14, 17, 05, 05))
XCTAssertEqual(Date.FromString("17:05, 14 February 2019 (UTC)"), Date.FromCalendar(2019, 2, 14, 17, 05))
XCTAssertEqual(Date.FromString("02-14-2019 17:05:05 GMT"),       Date.FromCalendar(2019, 2, 14, 17, 05, 05))
XCTAssertEqual(Date.FromString("02-13-2019 Tomorrow"),           Date.FromCalendar(2019, 2, 14))
XCTAssertEqual(Date.FromString("2019 Feb 14th Tomorrow at 5"),   Date.FromCalendar(2019, 2, 14, 17))

像这样:

extension Date
{


    public static func FromString(_ dateString: String) -> Date?
    {
        // Date detector.
        let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.date.rawValue)

        // Enumerate matches.
        var matchedDate: Date?
        var matchedTimeZone: TimeZone?
        detector.enumerateMatches(
            in: dateString,
            options: [],
            range: NSRange(location: 0, length: dateString.utf16.count),
            using:
            {
                (eachResult, _, _) in

                // Lookup matches.
                matchedDate = eachResult?.date
                matchedTimeZone = eachResult?.timeZone

                // Convert to GMT (!) if no timezone detected.
                if matchedTimeZone == nil, let detectedDate = matchedDate
                { matchedDate = Calendar.current.date(byAdding: .second, value: TimeZone.current.secondsFromGMT(), to: detectedDate)! }
        })

        // Result.
        return matchedDate
    }
}

2014年更新:

为此做了一个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!kit的一部分,抓住类别NSString + EPPZKit.h从GitHub。


2013年原始答案:

无论您不确定(或不在乎)字符串中包含的日期格式,都可以使用NSDataDetector解析date

//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; }];

它似乎不支持24小时制。例如NSString-> 2013-09-11 01:31:22 +0000转换为NSDate->2013-09-11 13:31:22 +0000
sooper 2013年

我最喜欢这个答案,因为原始日期字符串可以非常随意。在用户在文本字段而不是通过选择器输入日期的情况下,这非常有用。
凯尔2014年

2
此方法如何确定日期是DD / MM / yyyy还是MM / DD / yyyy?例如,如果输入为01/03/2014,结果将是什么?
ahmad 2014年

@ahmad我全心全意同意-如果您必须支持其他语言设置,则此方法可能行不通。
Frank Schmitt

@sooper XCTAssertEqual(Date.FromString("2013-09-11 01:31:22 +0000"), Date.FromCalendar(2013, 9, 11, 1, 31, 22))似乎很好。
GeriBorbás19年

33

使用固定格式的日期时,您需要将日期格式设置的语言环境设置为 "en_US_POSIX"

摘自《数据格式指南》

如果使用固定格式的日期,则应首先将日期格式器的语言环境设置为适合您的固定格式的语言环境。在大多数情况下,最佳选择的语言环境是en_US_POSIX,该语言环境专门设计用于产生美式英语结果, 而与用户和系统偏好设置无关。en_US_POSIX的时间也不变(如果美国在将来某个时候改变其格式化日期的方式,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"

解析自定义日期并将日期转换回相同的字符串格式:

let dateString = "01/02/10"

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

这是您可以根据需要自定义的所有元素:

在此处输入图片说明


如果多个线程访问这些方法怎么办?重新分配格式化程序的dateFormat会不会导致错误?使用变量(日期/时间/工作日)只是您的偏爱,还是这样做的好处,还是最佳实践?
lahmar 2015年

19

为什么不向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];

发现这确实有用。谢谢!
Thomas Johannesmeyer

6

用“ 10”代表年份不好,因为它可以是1910、1810等。您可能应该使用4位数字。

如果您可以将日期更改为

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];

4
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];

2
// 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];

1
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]);

1

使用此方法从转换NSStringNSdate

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

1

这些天,如果有人对在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()
}

1

日期到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

0

您可以为此使用扩展名。

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

0

最佳实践是建立一个通用类,在其中放置所有通用方法,几乎​​在所有项目中有用的方法,并在其中添加@Pavan建议的代码为:

+ (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;

}

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

这样,您就可以开始为应用构建干净的可重用代码。干杯!


0

根据Swift 2.2

您可以轻松地从String获取NSDate和从NSDate获取String。例如

首次设置日期格式

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

现在从字符串获取日期,反之亦然。

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

现在享受。


0

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;
}

0

上面的示例并非简单地为Swift 3.0+编写

更新-Swift 3.0+-将日期转换为字符串

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)

0

字符串至今

var dateFormatter = DateFormatter()
dateFormatter.format = "dd/MM/yyyy"

var dateFromString: Date? = dateFormatter.date(from: dateString) //pass string here

字符串日期

 var dateFormatter = DateFormatter()
 dateFormatter.dateFormat = "dd-MM-yyyy"
 let newDate = dateFormatter.string(from: date) //pass Date here
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.