using dates room java code example

Example 1: saving date type in room database

public class TimestampConverter {
    static DateFormat df = new SimpleDateFormat(Constants.TIME_STAMP_FORMAT);
    @TypeConverter
    public static Date fromTimestamp(String value) {
        if (value != null) {
            try {
                return df.parse(value);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return null;
        } else {
            return null;
        }
    }

Example 2: saving date type in room database

//Table names in SQLite are case insensitive.
@Entity(indices = {@Index(value = "first_name")})
public class User {
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "user_id")
    public long userId;
    @ColumnInfo(name = "first_name")
    public String firstName;
    @ColumnInfo(name = "created_date")
    @TypeConverters({TimestampConverter.class})
    public Date createDate;
    @ColumnInfo(name = "date_of_birth")
    @TypeConverters({DateConverter.class})
    public Date dob;
    @Embedded
    public Address address;
}

Tags:

Sql Example