0
votes

I have a java application that send measurements to an influxDB database.

I am adding points within my influxdb database. The points that I add each time that my program run have the current timestamp.

This is how I am adding my points (measurement building) :

    BatchPoints batchPoints;

    Date date = new Date();

    String beginofday = Constant.simpledateFormat.format(date);

    date = Constant.simpledateFormat.parse(beginofday);

    long timestamp = date.getTime();

    //adding points
    for buildings ... do
    Point point = Point.measurement("building").tag(tagsToAdd).fields(fieldsToAdd)
                        .time(timestamp, TimeUnit.NANOSECONDS).build();

    batchPoints.point(point);

My probem is that when I am requesting my database with such a request:

select count(tag) from building where time > (my timestamp)

I noticed that previous timestamp results are also counted, even that I am doing time>timestamp. And when I do a > instead of >= it counts only last ones. I noticed also that for the just previous timestamp, for example if I have timestamp like this 1540300800000 ns, influxdb add a 6 at the begining and it becomes 61540300800000 ms.

I really don't understand what is happening.

Any ideas?

1
I recommend you don’t use SimpleDateFormat and Date. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use Instant and other classes from java.time, the modern Java date and time API. - Ole V.V.

1 Answers

1
votes

java.time

    ZoneId zone = ZoneId.systemDefault();
    Instant beginofday = LocalDate.now(zone).atStartOfDay(zone).toInstant();

    long timestamp = beginofday.toEpochMilli();

    //adding points
    for buildings ... do
    Point point = Point.measurement("building").tag(tagsToAdd).fields(fieldsToAdd)
                        .time(timestamp, TimeUnit.MILLISECONDS).build();

I am using java.time, the modern Java date and time API.

What went wrong in your code

While I have not reproduced and tested, I believe that you confused milliseconds, 10^-3 seconds, and nanoseconds, 10^-9 seconds. date.getTime() gives you milliseconds since the epoch, but you are passing the number on in time(timestamp, TimeUnit.NANOSECONDS). If I take the start of the day today (Feb 21) in my time zone (CET) and use the milliseconds since the epoch as nanoseconds, I get 1970-01-01T00:25:50.703600Z. So I assume you got everything after some point around that time.

Other points:

  • The classes Date and SimpleDateFormat that you used are poorly designed and long outdated, so I suggest you avoid them. The modern java.time is so much nicer to work with.
  • Formatting your date-time into a date string and parsing it back is the detour for finding the start of the day.

Link

Oracle tutorial: Date Time explaining how to use java.time.