Spring Batch – read date field as a String in readers and convert it to other format

Before posting the question, I went through many links like: Using Spring Batch to parse date from file into LocalDateTime and Spring Batch – how to convert String from file to Date? etc but that doesn’t solve my problem.

In my project I’m reading csv file and creating one more csv out of it for the target system the way they want.

Source csv file has many fields and values like Apr 1 2022 12:00:00:000AM which is clearly a dateformat and I am reading this as String and while reading I want to convert it into yyyyMMdd format with the String value, so all values in my model class in String

<bean id="flatFileItemReader" class="org.springframework.batch.item.file.FlatFileItemReader">
        <property name="lineMapper">
            <bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
                <property name="lineTokenizer">
                    <bean class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer">
                        <property name="delimiter">
                            <util:constant static-field="org.springframework.batch.item.file.transform.DelimitedLineTokenizer.DELIMITER_TAB" />
                        </property>
                        <property name="names" value="field1, field2...... field60" />
                    </bean>
                </property>
                <property name="fieldSetMapper">
                    <bean class="XX.XX.XX.XX.MyBeanWrapperFieldSetMapper">
                        <property name="targetType" value="com.xxxxx.SomeModel" />
                        <property name="customEditors" value="" />
                    </bean>
                </property>
            </bean>
        </property>
    </bean>

Other code

public class MyBeanWrapperFieldSetMapper<T> extends BeanWrapperFieldSetMapper<T> {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM  d yyyy hh:mm:ss:SSSa", Locale.US);

    @Override
    protected void initBinder(DataBinder binder) {
        binder.registerCustomEditor(LocalDate.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                if (StringUtils.isNotEmpty(text)) {
                    setValue(LocalDate.parse(text, formatter));
                } else {
                    setValue(null);
                }
            }

            @Override
            public String getAsText() throws IllegalArgumentException {
                Object date = getValue();
                if (date != null) {
                    return formatter.format((LocalDate) date);
                } else {
                    return "";
                }
            }
        });
    }
}

Model

@AllArgsConstructor
@NoArgsConstructor
@Builder
@Data
public class SomeModel {
    private String id;
    private String createdDt;
    private String repliedDt;
    ....
    ...
}

I was able to solve this by using solution like this (The solution shown for another example)

<bean id="flatFileItemReader" class="org.springframework.batch.item.file.FlatFileItemReader" scope="step">
        <property name="resource" value="classpath:employee.csv" />
        <property name="linesToSkip" value="1" />
        <property name="lineMapper">
            <bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
                <property name="fieldSetMapper">
                    <!-- Mapper which maps each individual items in a record to properties in POJO -->
                    <bean class="com.example.EmployeeFieldSetMapper" />
                </property>
                <property name="lineTokenizer">
                    <!-- A tokenizer class to be used when items in input record are separated by specific characters -->
                    <bean class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer">
                        <property name="delimiter" value=","/>
                        <property name="names" value="empId,firstName,lastName,age,email,joiningDate" />
                    </bean>
                </property>
            </bean>
        </property>
    </bean>

FieldSetMapper

public class EmployeeFieldSetMapper implements FieldSetMapper<Employee> {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM  d yyyy hh:mm:ss:SSSa", Locale.US);
    DateTimeFormatter NEW_FORMAT = DateTimeFormatter.ofPattern("yyyyMMdd", Locale.US);

    @Override
    public Employee mapFieldSet(FieldSet fieldSet) throws BindException {
        String joiningDate = fieldSet.readRawString("joiningDate");
        return Employee.builder()
                .empId(fieldSet.readLong("empId"))
                .firstName(fieldSet.readString("firstName"))
                .lastName(fieldSet.readString("lastName"))
                .age(fieldSet.readInt("age"))
                .email(fieldSet.readString("email"))
                .joiningDate(joiningDate != null ?  formatFDate(joiningDate) : null)
                .build();
    }

    private String formatFDate(String value){
        LocalDateTime dateTime = LocalDateTime.parse(value, formatter);
        return dateTime.format(NEW_FORMAT);
    }
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật