How to convert form any date format to one date fo

2019-08-06 00:31发布

问题:

I'm getting different types of date formats from google servers. For my convenient i want convert all those date formats into one format. Here is below of different dates i'm getting in response.

17 Jun 14 12:26:20
Tue, 6 Mar 2018 05:16:51
8 Dec 2014 13:41:09 +0000
16 Sep 2014 16:08:47 -0400
29 Oct 2014 20:12:33 +0530
Tue, 8 Jul 2014 11:48:53 -0700
Tue, 03 Jun 2014 08:35:05 GMT
Tue, 03 Jun 2014 10:59:00 GMT
Wed, 04 Jun 2014 12:26:52 GMT
Wed, 7 Mar 2018 17:44:11 +0530
Wed, 07 Mar 2018 11:29:00 +0530
Thu, 8 May 2014 12:06:27 +0300 (EAT)
Tue, 13 Mar 2018 12:01:19 +0000 (UTC)
Mon, 19 Mar 2018 04:24:34 -0700 (PDT)
Sat, 24 May 2014 11:31:57 +0200 (CEST)
Wed, 02 Apr 2014 23:39:15 +0500 (GMT+05:00)

How can i convert all date strings into this format 2015-09-07 05:42:23 +0000. Thanks in advance.

I've tried like below it works fine but for this date it retunrs Nil due to that crash in app --> Tue, 8 Sep 2015 11:28:17 +0580 . it returns nil.

    struct RegexFormat {
    let pattern : String
    let dateFormat : String
}

let dateFormatter : DateFormatter = {
    let formatter = DateFormatter()
    formatter.locale = Locale(identifier: "en_US_POSIX")
    return formatter
}()

let regexFormats = [RegexFormat(pattern:"\\w{3},\\s+\\d{1,2}\\s+\\w{3}\\s+\\d{4}\\s+\\d{1,2}:\\d{2}:\\d{2}\\s+[+-]\\d{4}", dateFormat:"E, dd MMM yyyy HH:mm:ss Z"),
                    RegexFormat(pattern:"\\w{3},\\s+\\d{1,2}\\s+\\w{3}\\s+\\d{4}\\s+\\d{1,2}:\\d{2}:\\d{2}\\s+\\w{3}", dateFormat:"E, dd MMM yyyy HH:mm:ss z"),
                    RegexFormat(pattern:"\\d{1,2}\\s+\\w{3}\\s+\\d{4}\\s+\\d{1,2}:\\d{2}:\\d{2}\\s+[+-]\\d{4}", dateFormat:"d MMM yyyy HH:mm:ss Z"),
                    RegexFormat(pattern:"\\d{1,2}\\s+\\w{3}\\s+\\d{2,4}\\s+\\d{1,2}:\\d{2}:\\d{2}", dateFormat:"dd MM yy HH:mm:ss")]

func dateConverterFromStringtoDate(from string : String) -> Date?
{
    for regexFormat in regexFormats {
        do {
            let regex = try NSRegularExpression(pattern: regexFormat.pattern)
            if let match = regex.firstMatch(in: string, range: NSRange(location: 0, length: string.utf16.count)) {
                let dateRange = Range(match.range, in: string)!
                dateFormatter.dateFormat = regexFormat.dateFormat
                return dateFormatter.date(from: String(string[dateRange]) )
            }
        } catch {
            continue
        }
    }
    return nil
}

I want to convert all the dates into this format. 2015-09-08 05:42:07 +0000

@vadian please suggest answer for above issue.

回答1:

You can try this:

If the Response is in String Format with two different date format:

    var dateStr = "\(element.value!)"

    var isWeekThere:Bool = false

    if dateStr.range(of:"Mon") != nil {
        isWeekThere = true
    }else  if dateStr.range(of:"Tue") != nil {
        isWeekThere = true
    }else  if dateStr.range(of:"Wed") != nil {
        isWeekThere = true
    }else  if dateStr.range(of:"Thu") != nil {
        isWeekThere = true
    }else  if dateStr.range(of:"Fri") != nil {
        isWeekThere = true
    }else  if dateStr.range(of:"Sat") != nil {
        isWeekThere = true
    }else  if dateStr.range(of:"Sun") != nil {
        isWeekThere = true
    }

    var format:String = String()
    dateStr = dateStr.replacingOccurrences(of: "\\s?\\(\\w+\\)", with: "", options: .regularExpression)
    let dateFormatter = DateFormatter()
    if isWeekThere == true{
        format = "E, d MMM yyyy HH:mm:ss Z"
    }else{
        format = "d MMM yyyy HH:mm:ss Z"
    }
    dateFormatter.dateFormat = format
    let date = dateFormatter.date(from: dateStr)
    print(date!)
    dateFormatter.dateFormat = "ddMMMMYYYY" // Any format you can pass here
    let convDate = dateFormatter.string(from: date!)
    print(convDate)

This is the Output

Edit

If it gets Crash with some Uneven format:

You can use

dateFormatter.dateFormat = "ddMMMMyyyy"

Thanks @vadian For suggestion

Edit if the Response is in Date Format

Then use like this:

let date = element.value! //Your response in date
print(date!)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "ddMMMMYYYY" // Any format you can pass here
let convDate = dateFormatter.string(from: date!)
print(convDate)


回答2:

The answers so far focused on getting the right format string to use with DateFormatter, which has its limits since your date string are in so many different formats.

I propose another approach: using NSDataDetector (a subclass of NSRegularExpression). This is the same class that Apple uses to highlight a date or phone number in an email to enable user interactions.

let dateStrings = """
17 Jun 14 12:26:20
Tue, 6 Mar 2018 05:16:51
8 Dec 2014 13:41:09 +0000
16 Sep 2014 16:08:47 -0400
29 Oct 2014 20:12:33 +0530
Tue, 8 Jul 2014 11:48:53 -0700
Tue, 03 Jun 2014 08:35:05 GMT
Tue, 03 Jun 2014 10:59:00 GMT
Wed, 04 Jun 2014 12:26:52 GMT
Wed, 7 Mar 2018 17:44:11 +0530
Wed, 07 Mar 2018 11:29:00 +0530
Thu, 8 May 2014 12:06:27 +0300 (EAT)
Tue, 13 Mar 2018 12:01:19 +0000 (UTC)
Mon, 19 Mar 2018 04:24:34 -0700 (PDT)
Sat, 24 May 2014 11:31:57 +0200 (CEST)
Wed, 02 Apr 2014 23:39:15 +0500 (GMT+05:00)
""".components(separatedBy: "\n")

let types = NSTextCheckingResult.CheckingType.date.rawValue
let detector = try NSDataDetector(types: types)

var dates = [Date?]()
for str in dateStrings {
    let fullRange = NSRange(str.startIndex..., in: str)
    detector.enumerateMatches(in: str, options: [], range: fullRange) { result, flags, stop in
        if let result = result, result.resultType == .date {
            dates.append(result.date)
        } else {
            dates.append(nil)
        }
    }
}

A couple caveats:

  • The detection can be undeterministic. For example, "May 11" (without the year) is interpreted to mean "May 11 of the current year".
  • Ambiguous strings like "5/11/2018" is interpreted according to the device's locale. With en-US, it's May 11; with en-GB it's November 5.

To save yourself a followup question, the date and time is assumed to be in the device's timezone. Take the first string for example: I'm in the EDT timezone so 12:26:20 EDT = 16:26:20 UTC. You will get 16:26:20 when you call print(dates[0]!) because Date is always printed in UTC.