如何在 Talend 作业中将本地时间转换为 UTC,反之亦然

How can I convert local time to UTC and vice versa in a Talend job

我有一个数据库(不是 SQL),其中的时间字段都填有当地时间。 我有一个带有 UTC 时间字段的数据库 (SQL)。现在我想在这些数据库之间交换信息,但只有我可以将本地时间转换为 UTC,反之亦然,我才能实现这一点。我怎样才能在 Talend 中实现这一目标?

我知道当地时间数据库里的数据,是荷兰当地时间。 (格林威治标准时间 +2(夏季)的格林威治标准时间 +1(冬季))

Examples:
23-10-2015 16:00 Local time => 23-10-2015 14:00 UTC  (and vice versa)
26-10-2015 16:00 Local time => 26-10-2015 15:00 UTC  (and vice versa)

下面的截图有一个

tFixedFlowInput_1 - 使用 localDateTime(已填充)和 utcDateTime(未填充)定义模式

tJavaRow_1 - 在 localDateTime 上执行 Central/Europe 到 UTC 时区的对话并填充 utcDateTime。这是唯一必不可少的部分。

tLogRow_1 - 显示结果

接下来,为 tFixedFlowInput 设置架构并添加一些数据

下一步...设置 tJavaRow_1 组件

tJavaRow_1 高级设置/导入如下:

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.text.ParseException;

tJavaRow_1基本设置(真实代码)如下:

请注意,try 和 catch 块已被注释掉,以便抛出异常,Talend Job 可以处理它们。

使用了两个 SimpleDateFormat 实例,每个实例都与一个时区相关联。 localDateTime 通过源格式化程序进行解析。然后,目标格式化程序用于将日期转换为 UTC 并将其 return 作为原始格式的字符串。从 UTC 回到本地是一个微不足道的变化。

String BASE_FORMAT = "dd-MM-yyyy HH:mm";
TimeZone utcTZ = TimeZone.getTimeZone("UTC");
TimeZone ceTZ = TimeZone.getTimeZone("Europe/Amsterdam");

SimpleDateFormat formatUTC = new SimpleDateFormat( BASE_FORMAT );
formatUTC.setTimeZone(utcTZ);

SimpleDateFormat formatCE = new SimpleDateFormat( BASE_FORMAT );
formatCE.setTimeZone(ceTZ); 

output_row.localDateTime = input_row.localDateTime;

// Commented out the try and catch, so the exception is thrown to Talend job
//try {
    Date dateTimeLocal = formatCE.parse(input_row.localDateTime);
    output_row.utcDateTime = formatUTC.format(dateTimeLocal);
//}       
//catch (ParseException pe) {
//  System.out.println( pe.getMessage());
//}

接下来,tLogRow_1只是显示流量上的数据。这是来自 运行 示例数据的示例。

我需要获取 UTC 的当前日期。因此,我创建了一个类型为日期和特定格式的列,如下所示:

在表达式生成器中我写了下面的表达式:

TalendDate.parseDate("yyyy-MM-dd HH:mm:ss", TalendDate.formatDateInUTC("yyyy-MM-dd HH:mm:ss", TalendDate.getCurrentDate()))

这就是我的解决方案!

另外,我发现如果你把一个叫做 tlogrow 的组件放在你想看到它的输出的另一个组件之后 - 那会 tlogrow 做 -> 它会打印你在控制台中每行的数据快照。对调试很有用

我也在这里主持对话:https://community.talend.com/s/question/0D55b00006CvD7aCAF/return-utc-date-object

希望对大家有用!