@@ -3,21 +3,64 @@ package com.yourbcabus.android.yourbcabus
33import com.beust.klaxon.Converter
44import com.beust.klaxon.JsonValue
55import java.lang.Exception
6- import java.text.SimpleDateFormat
7- import java.time.format.DateTimeFormatter
86import java.util.*
97
108@Target(AnnotationTarget .FIELD )
119annotation class KlaxonDate {
10+ class InvalidDateException : Exception ()
11+
1212 companion object : Converter {
1313 override fun canConvert (cls : Class <* >): Boolean = cls == Date ::class .java
1414
15+ private fun parseTimezone (str : String ): TimeZone = when (str) {
16+ " Z" -> TimeZone .getTimeZone(" UTC" )
17+ else -> TimeZone .getTimeZone(str)
18+ }
19+
1520 override fun fromJson (jv : JsonValue ): Any? {
16- throw Exception ()
21+ try {
22+ val str = jv.string!! .replace(" -" , " " ).replace(" :" , " " ).replace(" ." , " " )
23+
24+ val year = str.substring(0 .. 3 ).toInt()
25+ val month = str.substring(4 .. 5 ).toInt()
26+ val day = str.substring(6 .. 7 ).toInt()
27+
28+ var hour = 0
29+ var minute = 0
30+ var second = 0
31+ var millisecond = 0
32+ var tz: TimeZone = TimeZone .getTimeZone(" UTC" )
33+
34+ if (str.length > 8 ) {
35+ hour = str.substring(9 .. 10 ).toInt()
36+ minute = str.substring(11 .. 12 ).toInt()
37+ second = str.substring(13 .. 14 ).toInt()
38+
39+ if (str.length > 15 ) {
40+ if (str[15 ].isDigit()) {
41+ millisecond = str.substring(15 .. 17 ).toInt()
42+ if (str.length > 18 ) {
43+ tz = parseTimezone(str.substring(18 ))
44+ }
45+ } else {
46+ tz = parseTimezone(str.substring(15 ))
47+ }
48+ }
49+ }
50+
51+ val calendar: Calendar = GregorianCalendar ()
52+ calendar.timeZone = tz
53+ calendar.set(year, month - 1 , day, hour, minute, second)
54+ calendar.set(Calendar .MILLISECOND , millisecond)
55+
56+ return calendar.time
57+ } catch (e: Exception ) {
58+ throw InvalidDateException ()
59+ }
1760 }
1861
1962 override fun toJson (value : Any ): String {
20- throw Exception ()
63+ TODO ()
2164 }
2265 }
2366}
0 commit comments