Flink 时间戳转换:将时间戳转换为时间格式
在 Flink 中,可以使用 'org.apache.flink.api.common.functions.MapFunction' 接口来将时间戳转换为时间格式。具体步骤如下所示:
- 导入所需的类:
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import java.text.SimpleDateFormat;
import java.util.Date;
- 创建一个 'MapFunction' 实现类,实现 'map()' 方法:
public class TimestampToTimeFormat implements MapFunction<Long, Tuple2<Long, String>> {
@Override
public Tuple2<Long, String> map(Long timestamp) throws Exception {
// 将时间戳转换为时间格式
Date date = new Date(timestamp);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String timeFormat = sdf.format(date);
return new Tuple2<>(timestamp, timeFormat);
}
}
- 在 Flink 程序中使用 'MapFunction' 进行时间戳转换:
DataStream<Tuple2<Long, String>> result = inputDataStream.map(new TimestampToTimeFormat());
在上述代码中,'inputDataStream' 是一个包含时间戳的 'DataStream','result' 是转换后的 'DataStream',其中的时间戳已经被转换为指定的时间格式。根据实际需求,可以调整时间格式的格式化字符串。
原文地址: https://www.cveoy.top/t/topic/o2b5 著作权归作者所有。请勿转载和采集!