Merge pull request #252 from TouchInstinct/date_time_utils

Date time utils
This commit is contained in:
Kirill Nayduik 2022-04-18 12:23:44 +03:00 committed by GitHub
commit bf68537809
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 80 additions and 0 deletions

View File

@ -5,6 +5,8 @@ dependencies {
implementation "androidx.core:core"
implementation "androidx.annotation:annotation"
implementation "com.google.android.material:material"
implementation "net.danlew:android.joda"
implementation "junit:junit"
constraints {
implementation("androidx.core:core") {
@ -24,5 +26,17 @@ dependencies {
require '1.2.0-rc01'
}
}
implementation("net.danlew:android.joda") {
version {
require '2.10.2'
}
}
implementation("junit:junit") {
version {
require '4.13.2'
}
}
}
}

View File

@ -0,0 +1,32 @@
package ru.touchin.roboswag.core.utils
import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
/**
* Util object for handling some cases with DateTime e.g. parsing string to DateTime object
*/
object DateFormatUtils {
enum class Format(val formatValue: String) {
DATE_TIME_FORMAT("yyyy-MM-dd'T'HH:mm:ss.SSSZZ"),
DATE_FORMAT("yyyy-MM-dd"),
TIME_FORMAT("HH:mm:ssZ")
}
/**
* @return the result of parsed string value
* @param value is string value of date time in right format
* @param format is date time format for parsing string value.
* Default value is [Format.DATE_TIME_FORMAT]
* @param defaultValue is value returned in case of exception
*/
fun fromString(
value: String,
format: Format = Format.DATE_TIME_FORMAT,
defaultValue: DateTime? = null
): DateTime? = runCatching { value.parse(format.formatValue) }.getOrDefault(defaultValue)
private fun String.parse(format: String) = DateTimeFormat.forPattern(format).parseDateTime(this)
}

View File

@ -0,0 +1,34 @@
import org.joda.time.DateTime
import org.joda.time.DateTimeZone
import org.joda.time.tz.UTCProvider
import org.junit.Assert
import org.junit.Test
import ru.touchin.roboswag.core.utils.DateFormatUtils
class DateFormatUtilsTest {
init {
DateTimeZone.setProvider(UTCProvider())
}
@Test
fun `Assert Date format parsing`() {
val dateTime = DateFormatUtils.fromString(
value = "2015-04-29",
format = DateFormatUtils.Format.DATE_FORMAT
)
Assert.assertEquals(DateTime(2015, 4, 29, 0, 0, 0), dateTime)
}
@Test
fun `Assert Date format parsing with default value`() {
val currentDateTime = DateTime.now()
val dateTime = DateFormatUtils.fromString(
value = "2015-04-29",
format = DateFormatUtils.Format.DATE_TIME_FORMAT,
defaultValue = currentDateTime
)
Assert.assertEquals(currentDateTime, dateTime)
}
}