Skip to content

Instantly share code, notes, and snippets.

@scandar
Last active February 8, 2025 16:41
Show Gist options
  • Save scandar/43a28ff3eb4fd75f624e398dad357676 to your computer and use it in GitHub Desktop.
Save scandar/43a28ff3eb4fd75f624e398dad357676 to your computer and use it in GitHub Desktop.
package com.example.myapplication
import android.os.Build
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.annotation.RequiresApi
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.myapplication.ui.theme.MyApplicationTheme
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
import java.time.temporal.TemporalAccessor
import java.util.Locale
class MainActivity : ComponentActivity() {
@RequiresApi(Build.VERSION_CODES.O)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
MyApplicationTheme {
Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
Greeting(
modifier = Modifier.padding(innerPadding)
)
}
}
}
}
}
@RequiresApi(Build.VERSION_CODES.O)
@Composable
fun Greeting(modifier: Modifier = Modifier) {
// Custom date patterns for different locales
// this allows us to format the date differently for each locale
// based on localization team requirements
val dateMap = mapOf(
Locale.US to "MMM d",
Locale.GERMANY to "MMM d.",
Locale.CHINA to "MMM d日"
)
val dateUS = formatDateShort(LocalDate.now(), Locale.US) // "Feb 8
val dateDE = formatDateShort(LocalDate.now(), Locale.GERMANY, dateMap[Locale.GERMANY].orEmpty()) // "8. Feb."
val dateCH = formatDateShort(LocalDate.now(), Locale.CHINA, dateMap[Locale.CHINA].orEmpty()) // "2月8日"
Text(
text = " US $dateUS\n DE $dateDE \n CH $dateCH",
modifier = modifier
)
}
@RequiresApi(Build.VERSION_CODES.O)
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
MyApplicationTheme {
Greeting()
}
}
@RequiresApi(Build.VERSION_CODES.O)
fun formatDateShort(date: TemporalAccessor, locale: Locale, pattern: String = "MMM d"): String {
val formatter = DateTimeFormatter.ofPattern(pattern)
.withLocale(locale)
return formatter.format(date)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment