Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .changeset/chilly-tools-like.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
"posthog": patch
"posthog-android": patch
"posthog-server": patch
"posthog-android-surveys-compose": patch
"posthog-server-openfeature": patch
---

Avoid unnecessary Calendar allocations when reading device-clock timestamps.
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.posthog.internal

import com.posthog.PostHogInternal
import java.util.Calendar
import java.util.Date

/**
Expand All @@ -11,14 +10,11 @@ import java.util.Date
@PostHogInternal
public class PostHogDeviceDateProvider : PostHogDateProvider {
override fun currentDate(): Date {
val cal = Calendar.getInstance()
return cal.time
return Date()
}

override fun addSecondsToCurrentDate(seconds: Int): Date {
val cal = Calendar.getInstance()
cal.add(Calendar.SECOND, seconds)
return cal.time
return Date(System.currentTimeMillis() + seconds * 1000L)
}

override fun currentTimeMillis(): Long {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.posthog.internal

import kotlin.test.Test
import kotlin.test.assertTrue

internal class PostHogDeviceDateProviderTest {
private val provider = PostHogDeviceDateProvider()

@Test
fun `current date uses the wall clock`() {
val before = System.currentTimeMillis()
val actual = provider.currentDate().time
val after = System.currentTimeMillis()

assertTrue(actual in before..after)
}

@Test
fun `adding seconds uses elapsed milliseconds without integer overflow`() {
listOf(Int.MIN_VALUE, -3601, 0, 3601, Int.MAX_VALUE).forEach { seconds ->
val offset = seconds * 1000L
val before = System.currentTimeMillis() + offset
val actual = provider.addSecondsToCurrentDate(seconds).time
val after = System.currentTimeMillis() + offset

assertTrue(actual in before..after, "Unexpected date for $seconds seconds: $actual")
}
}
}
Loading