Date Format issue in Android 12 & 13 - java

I am using dd-MMM-yyyy format in String format in kotlin in android.
It returns "01-Sept-2022" as a result.
I want "01-Sep-2022" as result.
This issue shows up in android 12 & 13.
#JvmStatic
fun getCurrentDate(format: String): String {
val sdf = SimpleDateFormat(format)
val currentDate = sdf.format(Date())
return currentDate
}
How can I get my desired return value in all versions?

According to #deHaar SimpleDateFormat returns the formatted string depending on the Locale. Take a look at all locales and you will find the correct form you want. Below I added a snippet where you can easily find it. If you develop this app for the app store or for other public users you shouldn't change the Locale in SimpleDateFormat because the user in this region normally knows this format. The Locale.getDefault is also influenced by the Android system settings.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val out = findViewById<TextView>(R.id.out)
out.text = getCurrentDate("dd-MMM-yyyy")
}
fun getCurrentDate(format: String): String {
var result = ""
val locales = listOf<Locale>(Locale.CANADA, Locale.CANADA_FRENCH, Locale.CHINA, Locale.CHINESE,
Locale.ENGLISH, Locale.FRANCE, Locale.FRENCH, Locale.GERMAN, Locale.GERMANY, Locale.ITALIAN,
Locale.ITALY, Locale.JAPAN, Locale.JAPANESE, Locale.KOREA, Locale.KOREAN, Locale.PRC,
Locale.ROOT, Locale.SIMPLIFIED_CHINESE, Locale.TAIWAN, Locale.TRADITIONAL_CHINESE, Locale.UK, Locale.US)
locales.forEach {
val sdf = SimpleDateFormat(format, it)
result += sdf.format(Date()) + "\n"
}
return result
}
returns
04-Sep.-2022
04-sept.-2022
04-9月-2022
04-9月-2022
04-Sep-2022
04-sept.-2022
04-sept.-2022
04-Sept.-2022
04-Sept.-2022
04-set-2022
04-set-2022
04-9月-2022
04-9月-2022
04-9월-2022
04-9월-2022
04-9月-2022
04-Sep-2022
04-9月-2022
04-9月-2022
04-9月-2022
04-Sep-2022
04-Sep-2022

Related

Kotlin: How to format a list of LocalDateTime to String?

I have succedded to format LocalDateTime to String but now how can I do the same for a list ?
The first function works but the second one doesn't work.
Here my class
class DateFormat {
companion object {
const val PATTERN = "dd-MM-yyyy HH:mm:ss"
fun format(date: LocalDateTime): String {
val formatter = DateTimeFormatter.ofPattern(PATTERN)
return date.format(formatter)
}
fun formatList(date: List<LocalDateTime>): String {
val formatter = DateTimeFormatter.ofPattern(PATTERN)
return date.forEach {
format(formatter)
}
}
}
}
to return a list of strings you could do this
fun formatList(date: List<LocalDateTime>): List<String> {
val formatter = DateTimeFormatter.ofPattern(PATTERN)
return date.map { it.format(formatter) }
}
or even shorter by referring to your other function like this:
fun formatList(date: List<LocalDateTime>): List<String> {
return date.map { format(it)}
}
or even this to make it super short
fun formatList(date: List<LocalDateTime>) = date.map { format(it)}
Edit:
realized you could even write this
fun formatList(date: List<LocalDateTime>) = date.map(::format)
Based on your second method implementation, you should return list of string instead of single result.
Also I have updated argument for first method to accept DateTimeFormatter, which will be useful while calling from second method.
class DateFormat {
companion object {
const val PATTERN = "dd-MM-yyyy HH:mm:ss"
fun format(date: LocalDateTime, formatter: DateTimeFormatter): String {
return date.format(formatter)
}
fun formatList(date: List<LocalDateTime>): List<String> {
val listResult = listOf<String>()
val formatter = DateTimeFormatter.ofPattern(PATTERN)
date.forEach {
listResult.add(format(formatter))
}
return listResult
}
}
}
You would need to join your list elements to String. How a "good format" looks like is up to you, the example below will output your dates separated by a "|" - you can use any separator you want (note: this calls your first format function):
fun formatList(date: List<LocalDateTime>): String =
date.joinToString(separator = "|") { format(it) }
EDIT: if you are on Android, note that the usage of DateTimeFormatter requires API level 26.

How to highlight days from API in highlighable calendar in Kotlin?

I have API that post and get dates:
this is the data class:
data class PlannerGet(
val date: String,
val endTime: String,
val id: Int,
val location: String,
val note: String,
val startTime: String,
val title: String
)
and i am using this library for the calendar:
https://github.com/VarunBarad/Highlightable-Calendar-View
now in the fragment i was able to highlight certain days like this:
HighlightableCalendarView.dayDecorators = listOf(
DayDecorator(
Calendar.getInstance().apply {
set(Calendar.DAY_OF_MONTH, 4)
},
Color.parseColor("#ffffff"),
Color.parseColor("#ff0000")
),
)
but i want to highlight the days from API
i tried to make it like this:
HighlightableCalendarView.dayDecorators = listOf(
DayDecorator(
Calendar.getInstance().apply {
set(PlannerGet.date)
},
Color.parseColor("#ffffff"),
Color.parseColor("#ff0000")
),
)
but i am having a problem with "set" it show "None of the following functions can be called with the arguments supplied."
i tried to add "toInt()" and still the same problem.
what is the correct way to achieve this?
This is because the params which you are passing do not match the required params.
Calendar.getInstance().apply {
set(Calendar.DAY_OF_MONTH, 4)
}
The set functions accept the int field, int value but you are passing the params as the string
PlannerGet.date
The function set
public void set(int field, int value) {
throw new RuntimeException("Stub!");
}
If you want the date to be passed from the API dates please convert the string dates to java Date object.
SOLUTION:
if (response?.body().toString() == "[]") {
}
else if (response.isSuccessful) {
response.body()?.forEach {
getplanner.add(it)
Log.e("gggg gggg",getplanner.toString())
Log.e("gggg ddddd",getplanner[0].date)
}
val list = arrayListOf<DayDecorator>()
for (dsds in getplanner) {
list.add( DayDecorator(
Calendar.getInstance().apply {
// getplanner[0].date
val input_date = dsds.date
val format1 = SimpleDateFormat("yyyy-MM-dd")
var dt1: Date? = null
dt1 = format1.parse(input_date)
val format2: DateFormat = SimpleDateFormat("dd")
val strMonth: String = format2.format(dt1)
val month = strMonth.toInt()
Log.e("dateinplanner", "" + month)
set(Calendar.DAY_OF_MONTH, month)
},
Color.parseColor("#ffffff"),
Color.parseColor("#1AB7B8")
))
}
HighlightableCalendarView.dayDecorators = list

Mocck issue with Instant.now().toString()

I have implemented an interface. There I am passing timestamp as parameter to a function. For geting the current time, I have used Instant.now().toString().
The function looks like this:
fun createId() {
val values = Record(name = "ABC", timestamp = Instant.now().toString())
interface_name.store(values)
}
#Test
fun `test1 for createId`() {
val values = Record(name = "ABC", timestamp = "2020-12-28")
every { interface_name.store(values) } just runs
}
This is giving me: Verification failed because the timestamp is different. I am unable to figure out how do I mock the Instant.now() so that I get the static timestamp while testing. Any help is appreciated.
Unit testing is easy when all the dependencies are passed as parameters. Hence instead of creating objects within the function, it is always good to design the function based on abstraction and pass the dependency as arguments.
fun createId(clock: Clock = Clock.systemUTC()): Record {
val values = Record(name = "ABC", timestamp = Instant.now(clock).toString())
interface_name.store(values)
return values
}
#Test
fun `test1 for createId`() {
val clock = Clock.fixed(Instant.parse("2021-01-01T00:00:00Z"), UTC)
val record = createId(clock)
assertEquals(Record(name = "ABC", timestamp = "2021-01-01T00:00:00Z"), record)
}

How do I convert Google's DateTime object to a long-type value?

I am trying to integrate a database with a web application that extracts event data from Google Calendar API which inputs the data into the database. The following code is identical to the Quickstart class provided by Google.
I basically want 'DateTime start' to be converted to 'long start'. I need the long value for SQL.
import com.google.api.client.util.DateTime;
// ...
DateTime now = new DateTime(System.currentTimeMillis());
Events events = service.events().list(calendarId)
.setTimeMin(now)
.setOrderBy("startTime")
.setSingleEvents(true)
.execute();
List<Event> items = events.getItems();
if (items.isEmpty()) {
System.out.println("No upcoming events found.");
} else {
System.out.println("Upcoming events");
for (Event event : items) {
DateTime start = event.getStart().getDateTime();
DateTime end = event.getEnd().getDateTime();
if (start == null) {
start = event.getStart().getDate();
}
System.out.printf("%s\n", start.toString());
Google has implemented the Rfc3339 parser in Google HTTP Client Library. You can try parsing it first and the use the DateTime.getValue() function to convert it into long.
You may also try using the DatetimeFormatter to format it to the way you want the value.
DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
.withZone(ZoneId.of("UTC"));
public void convertDatetime() {
String timeStamp = "2019-05-24T11:32:26.553955473Z";
DateTime dateTime = DateTime.parseRfc3339(timeStamp);
long millis = dateTime.getValue();
String result = formatter.format(new Date(millis).toInstant());

Exception in scala/java

I'm a beginner to scala programming and jvm languages. I want to convert a string in yyyy-MM-dd to date format like this:
import java.text.SimpleDateFormat
import java.util.Date
val format = new SimpleDateFormat("yyyy-MM-dd")
def strTodate(stringDate: String): Date = {
format.parse(stringDate)
}
How can I can take care of exception in case strTodate is called on a wrongly formatted string like strTodate("18/03/03") ? I'll like to handle the exception and also print the string
scala has three ways to handle errors.
Option: has None or Some
Try: has Success or Failure
Either: has left or right. Right is always right result.
I prefer Either of all and here is how you can do it as Either[String, Date] where Left is String, Right is Date.
Example,
import java.text.SimpleDateFormat
import java.util.Date
import scala.util.Try
import scala.util.{Failure, Success}
val format = new SimpleDateFormat("yyyy-MM-dd")
def strTodate(stringDate: String): Either[String, Date] = {
Try {
format.parse(stringDate)
} match {
case Success(s) => Right(s)
case Failure(e: ParseException) => Left(s"bad format: $stringDate")
case Failure(e: Throwable) => Left(s"Unknown error formatting : $stringDate")
}
}
val date1 = strTodate("2018-09-26")
println(date1) // Right(Wed Sep 26 00:00:00 PDT 2018)
val date2 = strTodate("2018/09/26")
println(date2) // Left(bad format: 2018/09/26)
Handling exceptions:
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.Date
object app {
val format = new SimpleDateFormat("yyyy-MM-dd")
def strTodate(stringDate: String): Either[Exception, Date] = {
try {
Right(format.parse(stringDate))
} catch {
case ioException : IOException =>
Left(ioException)
case e: Exception =>
Left(e)
}
}
def main(args: Array[String]) : Unit =
strTodate("2018-02-02") match {
case Right(date) => println(date)
case Left(err) => println(err.getMessage)
}
}

Categories

Resources