Talend - 在 "yyyy-MM-dd" 中转换 "EEE MMM dd hh:mm:ss z yyyy"

Talend - Transform "EEE MMM dd hh:mm:ss z yyyy" in "yyyy-MM-dd"

我从文件中收到一个日期,格式为:"EEE MMM dd hh:mm:ss z yyyy",我正在尝试将此值转换为日期 "yyyy-MM-dd"。为此,我正在使用:

TalendDate.parseDate("yyyy/MM/dd", TalendDate.formatDate("yyyy/MM/dd", TalendDate.parseDate("EEE MMM dd hh:mm:ss z yyyy",context.date)))

这里定义了context.date:

context.date = input_row.mtime_string;

但是当我 运行 我的 JavaRow 组件时,我收到以下错误:

组件异常 tJavaRow_1

"java.lang.RuntimeException: java.text.ParseException: Unparseable date: "Thu Aug 09 10:38:45 BST 2018"

我该如何解决这个问题?

非常感谢!

您可以使用以下代码片段实现格式 -

System.out.println(input_row.newColumn);
SimpleDateFormat parserSDF = new SimpleDateFormat("EEE MMM dd hh:mm:ss z yyyy", Locale.ENGLISH);
Date date = parserSDF.parse(input_row.newColumn);
String dDate = null; 
parserSDF = new SimpleDateFormat("yyyy-MM-dd");
dDate = parserSDF.format(date);
System.out.println(dDate);

此外,您需要导入以下库(tJavaRow 的高级设置部分)-

import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.Date;

我直接将文件中的输入值(在我的场景 tFileInputDelimited 中)传递给 tJavaRow 作为 - input_row.newColumn 然后使用 SimpleDateFormat class根据格式化模式解析和格式化日期。

阅读更多here

如果您想将日期转换为 LocalDate,那么以下代码可能会有所帮助:

private LocalDate getLocalDate(String date){
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd hh:mm:ss z yyyy", Locale.getDefault());
        return LocalDate.parse(date, formatter);
    }

获得 LocalDate 后,您可以将其转换为任何格式。正如问题所期望的那样,yyyy-MM-dd 然后只需在 LocalDate 对象上调用 toString()。

LocalDate curr = LocalDate.now();

System.out.println(curr.toString());

它会显示像“2019-11-20”这样的日期。

希望这对某人有所帮助。