You can use a java.time.format.DateTimeFormatterBuilder
to build a formatter with optional parts, where each optional part is a DateTimeFormatter
that can parse one of those formats.
I'm posting code in Java, because I'm not a Scala dev, but it shouldn't be hard to adapt it.
First you make the formatter for the date/time pattern:
DateTimeFormatter datetimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S");
Then you make another formatter to parse the timestamp. The value 1520877600
seems to be in seconds since unix epoch, so you can use the ChronoField.INSTANT_SECONDS
field:
DateTimeFormatter timestampFormatter = new DateTimeFormatterBuilder()
// parse timestamp value in seconds
.appendValue(ChronoField.INSTANT_SECONDS)
// create formatter
.toFormatter();
And then you join the 2 formatters above in a single one, making each formatter optional:
DateTimeFormatter fmt = new DateTimeFormatterBuilder()
// date/time
.appendOptional(datetimeFormatter)
// timestamp
.appendOptional(timestampFormatter)
// use JVM default timezone
.toFormatter().withZone(ZoneId.systemDefault());
Another detail is the withZone
method to set a timezone to be used by the formatter. That's because an unix timestamp represents a count of elapsed time since unix epoch, and the value 1520877600 can represent a different date and time, depending on the timezone you are.
I'm using the JVM default timezone (ZoneId.systemDefault()
), but you can choose it to whatever you need. Exampe: if I use ZoneId.of("America/New_York")
, the timestamp will be converted to New York timezone. Using a different timezone can affect the values of year and month, specially if the value corresponds to the first or last day of the month (and if I don't set a timezone, the parsing will fail for timestamps, because it needs a timezone to "translate" the timestamp to a date/time).
Anyway, as you want the year and month values, the best choice is to parse directly to a java.time.YearMonth
, which in turn can be used to get the correspondent int
values for year and month:
YearMonth ym = YearMonth.parse("2018-04-23 11:12:00.0", fmt);
int year = ym.getYear();
int month = ym.getMonthValue();
ym = YearMonth.parse("1520877600", fmt);
year = ym.getYear();
month = ym.getMonthValue();