Convert String With Unknown Format (Any Format) to Date

How to convert String to Date without knowing the format?

You cant!

If you have the date 2010-08-05 then it can be either 5th August 2010, or 8th May 2010 - you need to know the date format (or at least prioritise one format over the over) to tell them apart.

Convert string with unknown format (any format) to date

Xcode 11.4 • Swift 5.2 or later

You can use NSDataDetector as follow:

extension String {
var nsString: NSString { self as NSString }
var length: Int { nsString.length }
var nsRange: NSRange { .init(location: 0, length: length) }
var detectDates: [Date]? {
try? NSDataDetector(types: NSTextCheckingResult.CheckingType.date.rawValue)
.matches(in: self, range: nsRange)
.compactMap(\.date)
}
}


extension Collection where Iterator.Element == String {
var dates: [Date] { compactMap(\.detectDates).flatMap{$0}
}
}

Testing:

let dateStrings = ["January 3, 1966","Jan 3, 1966", "3 Jan 1966"]
for dateString in dateStrings {
if let dateDetected = dateString.detectDates?.first {
print(dateDetected)
// 1966-01-03 14:00:00 +0000
// 1966-01-03 14:00:00 +0000
// 1966-01-03 14:00:00 +0000
}
}


let dateStrings = ["January 3, 1966","Jan 3, 1966", "3 Jan 1966"]

for date in dateStrings.dates {
print(date)
// 1966-01-03 14:00:00 +0000
// 1966-01-03 14:00:00 +0000
// 1966-01-03 14:00:00 +0000
}

Convert unknown format strings to datetime objects?

The dateutil module has a date parser which can parse date strings in many formats.

For example,

In [13]: import dateutil.parser as parser

In [14]: parser.parse("19970902T090000")
Out[14]: datetime.datetime(1997, 9, 2, 9, 0)

In [15]: import datetime as dt

In [16]: now = dt.datetime.now()

In [17]: now.isoformat()
Out[18]: '2012-11-06T15:08:51.393631'

In [19]: parser.parse('2012-11-06T15:08:51.393631')
Out[19]: datetime.datetime(2012, 11, 6, 15, 8, 51, 393631)

In [20]: parser.parse('November 6, 2012')
Out[20]: datetime.datetime(2012, 11, 6, 0, 0)

Note that some datetime strings can be ambiguous: 10-09-2003 could mean October 9 or September 10, for example. dateutil has parameters like dayfirst and yearfirst to handle this:

In [21]: parser.parse("10-09-2003")
Out[21]: datetime.datetime(2003, 10, 9, 0, 0)

In [22]: parser.parse("10-09-2003", dayfirst = True)
Out[22]: datetime.datetime(2003, 9, 10, 0, 0)

In [23]: parser.parse("10-09-03", yearfirst = True)
Out[23]: datetime.datetime(2010, 9, 3, 0, 0)

convert string in unknown format to date in c#

Use DateTime.ParseExact with the different patterns as formats.

If after parsing you really need to use a string representation, use the ToString method of the DateTime with the explicit format that you're interested in (so that it is culture-invariant). It's better however to keep the DateTime because this is format-agnostic.

compare two dates of unknown format

You can't guess the format based on the provided string. For example the string "10/7/2019" would be ambiguous, since it allows both dd/mm/yyyy and mm/dd/yyyy. If you know the locale you can simply provide it to the .moment() function.

moment(dateString, "L", locale);

var dateString = "10/7/2019",    display = "YYYY-MM-DD",    en_us = moment(dateString, "L", "en-us"),    en_gb = moment(dateString, "L", "en-gb");
console.log( en_gb.format(display), "<", en_us.format(display), "//=>", en_gb.isBefore(en_us));

converting string representation of unknown date-format to Date in java

well this is not a real "java" solution, but if you have found a Javascript one, than you can use the Javascript solution in java using the ScriptEngine.

just a little quick and dirty... :)

here is a sample code:

public static void main(String[] args) throws ScriptException, ParseException {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
String[] dateStrings = new String[] {
"2015-10-14T16:41:42.000Z",
"2015-10-14T19:01:53.100+01:00",
"2015-10-14 05:20:29" };

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
for (String d : dateStrings) {
String script = "new Date('" + d + "')";
Object eval = engine.eval(script);
Date parsed = sdf.parse(eval.toString().replace("[Date ", "").replace("]", ""));
System.out.println(eval + " -> " + parsed);

}

}

that prints out:

[Date 2015-10-14T16:41:42.000Z] -> Wed Oct 14 18:41:42 CEST 2015
[Date 2015-10-14T18:01:53.100Z] -> Wed Oct 14 20:01:53 CEST 2015
[Date 2015-10-14T03:20:29.000Z] -> Wed Oct 14 05:20:29 CEST 2015

The eval.toString() part can be improved obviously. as the locale settings...

Converting date string in unknown format to datetime

The parse() method of dateutil is very flexible and will parse almost anything you throw at it.

However, because of that flexibility, if your input is limited to a certain number of patterns, custom code that checks for those patterns then uses datetime.datetime.strptime() could easily beat it.

Since this depends entirely on the number of patterns you need to test for, the only thing you can do is measure which one will be faster for your specific usecases.

How to get date format of a list of unknown format strings?

You can create a list with all known formats and try to parse your dates with those. If no error occurs for a format, then it's your input list's format.

from datetime import datetime

date_list = ['2020-02-28', '2020-03-11', '2020-03-12', '2020-04-01']
date_list2 = ['2020-02-02', '2020-12-11', '2020-13-11', '2020-29-12']
date_list3 = ['10-02-2002', '04-12-2011', '09-10-1911', '20-12-1912']


def define_dformat(dl):
dformats = ['%Y-%m-%d', '%Y-%d-%m', '%d-%m-%Y']
for dformat in dformats:
for date in dl:
try:
datetime.strptime(date, dformat)
except ValueError:
break
else:
return dformat
raise Exception("date list didn't match with any known formats")


print(define_dformat(date_list))
print(define_dformat(date_list2))
print(define_dformat(date_list3))

%Y-%m-%d
%Y-%d-%m
%d-%m-%Y



Related Topics



Leave a reply



Submit