greendao timestamp formatting issues and convert

greendao timestamp formatting issues and convert

Encountered an interesting little problem when using greendao when mapping timestamp field sqlite database to date java time, time of occurrence is not correct, the value date becomes 1970-00-00 00:00:xx, and then view the next date of the getTime()method and found this epoch value is actually the correct time of the year turned out 2018, the rest are not converted over. In stackoverflow also have personal experience the same problem, see https://stackoverflow.com/questions/22172331/greendao-date-type-returning-1-jan-1970 .

problem causes

Tracked down the code and found that the problem is actually quite simple: when the dump data and put into sqlite, this timestamp field save the file as string, value 2018-11-23 12:31:25; greendao dao when generating the code, date fields using the cursor getLong()read (by android the sqlite standard, when reading timestamp, use getLong()), resulting in year 2018 made only when the format conversion, use this number as the epoch values to create a Date.

The above process may be dao on IntelliJ, greendao generated check readEntity()method code, the file location is 'build / generated / source / <package name> / xxxDao'. readEntity()The method of generating a solid object from the cursor, it will take the data from the cursor at every field and field initialized.

Solution

Make a generic StringDateConverter, to convert the string to the correct date format:

public class StringDateConverter implements PropertyConverter<Date, String> {
    private final static List<String> FORMATS = Arrays.asList(
            "yyyy-MM-dd HH:mm:ss"
    );

    @Override
    public Date convertToEntityProperty(String databaseValue) {
        Date date = null;
        for (String format : FORMATS) {
            try {
                date = DateUtils.parseDate(databaseValue, format);
                break;
            } catch (ParseException e) {
                // do nothing
            }
        }
        if (date == null) {
            date = new Date(0);
        }
        return date;
    }

    @Override
    public String convertToDatabaseValue(Date entityProperty) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(entityProperty);
    }
}

Then on each of the Date field, plus a converter:

@Entity(nameInDb = "t_user")
public class User {
    ...
    @Property(nameInDb = "birthday")
    @Convert(converter = StringDateConverter.class, columnType = String.class)
    private Date birthday;
    ...
}

After dao regenerate the code, you can see the corresponding field conversion has been done:

...birthdayConverter.convertToEntityProperty(cursor.getString(offset + 7));

Read data is normal.

Guess you like

Origin www.cnblogs.com/fengyc/p/11101951.html