Как получить текущее время и дату в Android с помощью Jetpack Compose?
Много раз в приложениях для Android мы должны фиксировать текущую дату и время в нашем приложении для Android, чтобы мы могли обновлять наши данные в соответствии с этим. В этой статье мы рассмотрим, как получить текущее время и дату в нашем приложении для Android с помощью Jetpack Compose .
Пошаговая реализация
Шаг 1. Создайте новый проект в Android Studio.
Чтобы создать новый проект в Android Studio, обратитесь к разделу «Как создать/запустить новый проект в Android Studio». При выборе шаблона выберите «Пустая активность создания» . Если вы не нашли этот шаблон, попробуйте обновить Android Studio до последней версии. Мы продемонстрировали приложение на Kotlin, поэтому убедитесь, что вы выбрали Kotlin в качестве основного языка при создании нового проекта.
Шаг 2: Работа с файлом MainActivity.kt
Перейдите в приложение > java > имя пакета вашего приложения > файл MainActivity.kt и добавьте в него приведенный ниже код. В код добавлены комментарии для более подробного ознакомления.
Kotlin
package com.example.newcanaryproject import android.Manifest.permission.READ_EXTERNAL_STORAGEimport android.app.Activityimport android.content.BroadcastReceiverimport android.content.Contextimport android.content.Intentimport android.content.IntentFilterimport android.content.pm.PackageManagerimport android.content.res.ColorStateListimport android.database.Cursorimport android.os.Bundleimport android.os.Environmentimport android.provider.MediaStoreimport android.util.Logimport android.widget.TextClockimport android.widget.Toastimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContentimport androidx.compose.foundation.ExperimentalFoundationApiimport androidx.compose.foundation.Imageimport androidx.compose.foundation.layout.*import androidx.compose.foundation.lazy.GridCellsimport androidx.compose.foundation.lazy.LazyVerticalGridimport androidx.compose.material.*import androidx.compose.runtime.*import androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.res.colorResourceimport androidx.compose.ui.res.painterResourceimport androidx.compose.ui.semantics.Role.Companion.Imageimport androidx.compose.ui.text.font.FontWeightimport androidx.compose.ui.text.style.TextAlignimport androidx.compose.ui.unit.*import androidx.compose.ui.viewinterop.AndroidViewimport androidx.core.app.ActivityCompatimport androidx.core.app.ActivityCompat.requestPermissionsimport androidx.core.content.ContextCompatimport androidx.localbroadcastmanager.content.LocalBroadcastManagerimport coil.compose.rememberImagePainterimport com.example.newcanaryproject.MainActivity2import com.example.newcanaryproject.Rimport com.example.newcanaryproject.ui.theme.*import java.io.Fileimport java.text.SimpleDateFormatimport java.util.* class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { NewCanaryProjectTheme { // on below line we are specifying // background color for our application Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background ) { // on below line we are specifying theme as scaffold. Scaffold( // in scaffold we are specifying top bar. topBar = { // inside top bar we are specifying background color. TopAppBar(backgroundColor = greenColor, // along with that we are specifying title // for our top bar. title = { // in the top bar we are specifying tile as a text Text( // on below line we are specifying text // to display in top app bar. text = "GFG", // on below line we are specifying modifier // to fill max width. modifier = Modifier.fillMaxWidth(), // on below line we are specifying text alignment. textAlign = TextAlign.Center, // on below line we are specifying // color for our text. color = Color.White ) }) }) { // on below line we // are calling our function. displayTxtClock() } } } } }} // on below line we are creating a // function to get current date and time.@Composablefun displayTxtClock() { // on below line we are // creating a column on below sides. Column( // on below line we are adding padding // padding for our column and filling the max size. Modifier .fillMaxSize() .fillMaxHeight() .fillMaxWidth(), // on below line we are adding // horizontal alignment for our column horizontalAlignment = Alignment.CenterHorizontally, // on below line we are adding // vertical arrangement for our column verticalArrangement = Arrangement.Center ) { Text( // on below line we are specifying text to display. text = "Current Date and Time in Android", // on below line we are specifying // modifier to fill max width. modifier = Modifier.fillMaxWidth(), // on below line we are // specifying text alignment. textAlign = TextAlign.Center, // on below line we are // specifying color for our text. color = Color.Black, // on below line we are specifying font weight fontWeight = FontWeight.Bold, // on below line we are updating font size. fontSize = 25.sp, ) // on below line we are creating a spacer. Spacer(modifier = Modifier.height(20.dp)) // on below line we are creating and initializing // variable for simple date format. val sdf = SimpleDateFormat(""Date
"dd-MM-yyyy "
and
Time
"HH:mm:ss z") // on below line we are creating a variable for // current date and time and calling a simple // date format in it. val currentDateAndTime = sdf.format(Date()) Text( // on below line we are // specifying text to display. text = currentDateAndTime, // on below line we are specifying // modifier to fill max width. modifier = Modifier.fillMaxWidth(), // on below line we are // specifying text alignment. textAlign = TextAlign.Center, // on below line we are specifying // color for our text. color = Color.Black, // on below line we are specifying font weight fontWeight = FontWeight.Bold, // on below line we are updating font size. fontSize = 25.sp, ) }} |
Теперь запустите ваше приложение, чтобы увидеть результат.
Выход: