Simplest way to get First and last day of every month of the year with JodaTime

StackOverflow https://stackoverflow.com/questions/22780894

  •  25-06-2023
  •  | 
  •  

Вопрос

I'm storing date/times in a Sqlite table as Long values, so they end up looking something like 138329292113. The problem with this, while easy to store, is that it's harder to sort on. I am working on a filter function that ties in to a highcharts graph, to allow users to filter the graph to certain date ranges, and therefore need to be able to filter and sum the results by day, month, etc from the tables.

The only way so far I've thought of to do this, is with the following lines of code, which will need to be repeated for each month:

LocalDate ld2 = new LocalDate();
long januaryStart = ld2.monthOfYear().withMinimumValue().dayOfMonth().withMinimumValue().toDateTimeAtStartOfDay().getMillis();
long januaryEnd = ld2.monthOfYear().withMinimumValue().dayOfMonth().withMaximumValue().toDateTimeAtMidnight().getMillis();

I would then simply add a month to January to get February, etc. Using this, I should be able to get the millis for the beginning of the month, and the end of the month, passing this to a SQL statement to return a sum based on this range. I've been thinking if there is a simpler way to do this for every month (or other time interval) but so far this is all I could come up with.

is there a simpler way to do this that I'm missing?

Thanks in advance!

Это было полезно?

Решение

I think you tried a little bit too much:

LocalDate date = new LocalDate(); // note: current date in system time zone
date = date.withMonthOfYear(1); // set to January

while (date.getMonthOfYear() < 12) {
  long monthStart = date.dayOfMonth().withMinimumValue().toDateTimeAtStartOfDay().getMillis();
  long monthEnd = date.dayOfMonth().withMaximumValue().toDateTimeAtStartOfDay().getMillis();
  // store your longs in db
  date = date.plusMonths(1);
}

Personally I would like you to reconsider your decision to store the results as absolute long-millis. This approach makes it difficult to change the stored timestamps back to plain dates. Sometimes there will not be a reversible 1:1-mapping. ANSI-SQL has the column type definition of a DATE without time or timezone. In JDBC you can then use the class java.sql.Date. Generally you should choose the data type which is most appropriate for your domain use case. A UNIX-like timestamp in millis should not be seen as all-purpose solution. So if you decide to choose a plain date instead then your code can be simplified further! Then no need for conversion to DateTime at begin of day (even timezone-dependent).

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top