Created
November 14, 2019 06:08
-
-
Save DipaliShah/60db6b2ddda46b398b6566e24d37a982 to your computer and use it in GitHub Desktop.
A custom Date formatter to format dates coming from Server in Moshi Way. An alternative to GSON builder .setDateFormat method as there is no resembling method in Moshi we need to create Adapter for this.
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
// Custom Type Adapters for Moshi | |
val userMoshi = Moshi.Builder().add(CustomDateAdapter()).add(T).build() | |
//add Moshi builder in Converter Facrory | |
val retrofit = Retrofit.Builder() | |
.baseUrl("https://dl.dropboxusercontent.com/") | |
.addConverterFactory(MoshiConverterFactory.create(userMoshi)) | |
.addCallAdapterFactory(RxJava2CallAdapterFactory.create()) | |
.build() | |
// Custom Date formatter for call the date string coming from server in single date format to Date object. | |
class CustomDateAdapter { | |
/* | |
* Date Formatter for date string matching this 2020-11-06T22:39:00+11:00 | |
* | |
* */ | |
private val DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ssXXX" | |
var dateAdapter: Any = object : Any() { | |
val dateFormat: DateFormat | |
init { | |
dateFormat = SimpleDateFormat(DATE_FORMAT, Locale.getDefault()) | |
dateFormat.timeZone = TimeZone.getTimeZone("GMT") | |
} | |
@ToJson | |
@Synchronized | |
fun dateToJson(d: Date): String { | |
return dateFormat.format(d) | |
} | |
@FromJson | |
@Synchronized | |
@Throws(ParseException::class) | |
fun dateFromJson(s: String): Date { | |
return dateFormat.parse(s) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment