1

i found this code in java that reads the values inside a table, and tells strings from numbers.

i want to read values from my table considering everything string, including dates .

how to edit this code to make it read all as strings


    public String valueStr;
    public BigDecimal valueNumber;

    public String getString() {
        return valueStr;
    }

    public void setNull() {
        valueNumber = null;
        valueStr = null;
    }

    public void setString(String value) {
        valueStr = value;
        valueNumber = null;
    }

    public BigDecimal getNumber() {
        return valueNumber;
    }

    public void setNumber(BigDecimal value) {
        valueStr = null;
        valueNumber = value;
    }

    public LocalDate getDate() {
        if (getNumber() == null)
            return null;
        return LocalDate.ofEpochDay(((long) getNumber().doubleValue()) - 25569);
    }

    public void setDate(LocalDate date) {
        valueStr = null;
        valueNumber = BigDecimal.valueOf(date.toEpochDay() + 25569);
    }

    public LocalDateTime getDateTime() {
        if (getNumber() == null)
            return null;
        return LocalDateTime.ofEpochSecond((long) (getNumber().doubleValue() - 25569) * 86400, 0, ZoneOffset.UTC);
    }

    public void setDateTime(LocalDateTime dateTime) {
        valueStr = null;
        valueNumber = BigDecimal.valueOf(dateTime.toEpochSecond(ZoneOffset.UTC) / 86400. + 25569);
    }
}
  • Is it not possible to use `toString()`? Define the signature of the your `set` method to take `Object`. And then simply call `.toString()` on the incoming value (with null checks, of course). Eg, `public void setValue(Object o){ if( o!=null ) this.valueStr = o.toString(); }` – Sree Kumar Dec 07 '21 at 10:40
  • Why use this code at all if you want to use strings? – tgdavies Dec 07 '21 at 10:41
  • “i want to read values from my table…” What table? I don’t see any reading of a table in that code. – VGR Dec 07 '21 at 13:24
  • the table is acctually a file input i add in main when i want to test – codeitforfuture Dec 07 '21 at 13:50
  • @codeitforfuture have you tried my answer? – Turtle Dec 07 '21 at 15:58

1 Answers1

0

For BigDecimal use toString()

valueStr = value.toString();

For LocalDate / LocalDateTime use java.time.format.DateTimeFormatter

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
valueStr = value.format(formatter);

For more on how to use Date time patterns see this

Turtle
  • 667
  • 1
  • 6
  • 18