How to Handle Two Possible Date Formats

How to handle two possible date formats?

Try both formats:

let parser1 = DateFormatter()
parser1.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"

let parser2 = DateFormatter()
parser2.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"

func parse(_ dateString: String) -> Date? {
let parsers = [parser1, parser2]

for parser in parsers {
if let result = parser.date(from: dateString) {
return result
}
}

return nil
}

print(parse("2017-01-18T10:49:00Z"))
print(parse("2017-02-14T19:53:38.1173228Z"))

Also note that the Z in the format is not a literal value.

How to handle multiple date formats?

Check if the date string contains a slash and set the date format accordingly:

if mydate.contains("/") {
df.dateFormat = "MM/dd/yyyy"
} else {
df.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
}

How to parse custom multiple Date formats in Java

You can use [] to define the optional parts within a pattern. Additionally you need to set defaults to not get an exception when no time is supplied.

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("yyMMdd['h'HH]")
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.toFormatter();

String dateString1 = "201028h05";
LocalDateTime date1 = LocalDateTime.parse(dateString1, formatter);
System.out.println(date1);

String dateString2 = "201028";
LocalDateTime date2 = LocalDateTime.parse(dateString2, formatter);
System.out.println(date2);

Output:

2020-10-28T05:00
2020-10-28T00:00

How to parse dates in multiple formats using SimpleDateFormat

You'll need to use a different SimpleDateFormat object for each different pattern. That said, you don't need that many different ones, thanks to this:

Number: For formatting, the number of pattern letters is the minimum number of digits, and shorter numbers are zero-padded to this amount. For parsing, the number of pattern letters is ignored unless it's needed to separate two adjacent fields.

So, you'll need these formats:

  • "M/y" (that covers 9/09, 9/2009, and 09/2009)
  • "M/d/y" (that covers 9/1/2009)
  • "M-d-y" (that covers 9-1-2009)

So, my advice would be to write a method that works something like this (untested):

// ...
List<String> formatStrings = Arrays.asList("M/y", "M/d/y", "M-d-y");
// ...

Date tryParse(String dateString)
{
for (String formatString : formatStrings)
{
try
{
return new SimpleDateFormat(formatString).parse(dateString);
}
catch (ParseException e) {}
}

return null;
}

Simple way to unify multiple date formats?

Actually, despite my comment, something like this might work:

COALESCE(STR_TO_DATE(val, "formatcandidate1")
, STR_TO_DATE(val, "formatcandidate2")
, STR_TO_DATE(val, "formatcandidate3")
, STR_TO_DATE(val, "formatcandidate4")
, [etc...]
) AS dateVal

Multiple date format in on column

Each string representation format potentially can require own conversion date style, therefore:

with cte as (
select '2017-06-14' DateString
union all
select '04/09/15' -- expected dateformat: dd/mm/yy
)

select
case when DateString like '%-%-%' then CONVERT(DATE, DateString, 20) -- ODBC canonical
when DateString like '%/%/%' then CONVERT(DATE, DateString, 3) -- French
else null
end
from cte

Results to:

2017-06-14
2015-09-04

How to format multiple date formats into single date in python

In an ideal world, you know the format of your inputs.

Where this is not possible, I recommend you use a 3rd party library for mixed format dates.

Two libraries that come to mind are dateutil (via dateutil.parser.parse) and pandas (via pandas.to_datetime). Below is an example implementation with the former.

Note the only occasion when parser.parse was unsuccessful had to be covered with a manual conversion via datetime.strptime. datetime is part of the standard Python library.

from datetime import datetime
from dateutil import parser

list1 = ["30-4-1994", "1994-30-04", "30/04/1994",
"30-apr-1994", "30/apr/1994","1994-30-apr"]

def converter(lst):
for i in lst:
try:
yield parser.parse(i)
except ValueError:
try:
yield parser.parse(i, dayfirst=True)
except ValueError:
try:
yield datetime.strptime(i, '%Y-%d-%b')
except:
yield i

res = list(converter(list1))

# [datetime.datetime(1994, 4, 30, 0, 0),
# datetime.datetime(1994, 4, 30, 0, 0),
# datetime.datetime(1994, 4, 30, 0, 0),
# datetime.datetime(1994, 4, 30, 0, 0),
# datetime.datetime(1994, 4, 30, 0, 0),
# datetime.datetime(1994, 4, 30, 0, 0)]

You can then format into strings any way you like using datetime.strptime:

res_str = [i.strftime('%d-%m-%Y') for i in res]

# ['30-04-1994',
# '30-04-1994',
# '30-04-1994',
# '30-04-1994',
# '30-04-1994',
# '30-04-1994']


Related Topics



Leave a reply



Submit