Created
December 8, 2020 08:09
-
-
Save antoniomaria/d157b1e37c148bdeb797e5e348a4de11 to your computer and use it in GitHub Desktop.
Jodatime round to period
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object DateTimeUtils { | |
import org.joda.time.format.ISODateTimeFormat | |
import org.joda.time.{DateTime, DateTimeZone, LocalDateTime, Period} | |
/** | |
* Round a given dateTime to next period. Examples | |
* <pre> | |
* 2018-04-10T09:59:59, 60m period -> 2018-04-10T10:00:00 | |
* 2018-04-10T10:00:00, 60m period -> 2018-04-10T10:00:00 | |
* 2018-04-10T10:00:01, 60m period -> 2018-04-10T11:00:00 | |
* </pre> | |
* @return | |
*/ | |
def roundCeilToPeriod(dataTime: LocalDateTime, period: Period): LocalDateTime = { | |
val previousPeriod = roundFloorToPeriod(dataTime, period) | |
if (previousPeriod.equals(dataTime)) { | |
dataTime | |
} else { | |
previousPeriod.plusMillis(period.toStandardDuration.getMillis.toInt) | |
} | |
} | |
/** | |
* Round a given dateTime to previous period. Examples | |
* <pre> | |
* 2018-04-10T11:00:01, 60m period -> 2018-04-10T11:00:00 | |
* 2018-04-10T11:00:00, 60m period -> 2018-04-10T11:00:00 | |
* 2018-04-10T10:59:59, 60m period -> 2018-04-10T10:00:00 | |
* </pre> | |
* @return | |
*/ | |
def roundFloorToPeriod(dataTime: LocalDateTime, period: Period): LocalDateTime = { | |
new LocalDateTime() | |
.withYear(dataTime.getYear) | |
.withMonthOfYear(dataTime.getMonthOfYear) | |
.withDayOfMonth(dataTime.getDayOfMonth) | |
.withMillisOfDay(dataTime.getMillisOfDay - (dataTime.getMillisOfDay % period.toStandardDuration.getMillis).toInt) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment