Kotlin date to string format

How do you format date and time in Android using Kotlin?

This example demonstrates how to format date and time in Android using Kotlin.

Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

Example

Step 3 − Add the following code to src/MainActivity.kt

import android.os.Bundle import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import java.text.SimpleDateFormat import java.util.* class MainActivity : AppCompatActivity() < override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" val textView: TextView = findViewById(R.id.textView) val calendar: Calendar = Calendar.getInstance() val simpleDateFormat = SimpleDateFormat("EEEE, dd-MMM-yyyy hh-mm-ss a") val dateTime = simpleDateFormat.format(calendar.time) textView.text = dateTime >>

Step 4 − Add the following code to androidManifest.xml

Let’s try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project’s activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen

Источник

How to format in kotlin date in string or timestamp to my preferred format?

Formatting a date in Android can be a complex task, especially when working with different time zones and locales. In Kotlin, you can use the SimpleDateFormat class to format a date and time into a string representation, or parse a string into a Date object. The SimpleDateFormat class provides a variety of patterns that you can use to format the date and time, but it can be challenging to get the formatting just right. This tutorial will guide you through the process of formatting a date in Kotlin and provide you with solutions to some common problems you may encounter along the way.

Method 1: SimpleDateFormat Class

To format a date in Kotlin using the SimpleDateFormat class, you can follow these steps:

  1. Create an instance of SimpleDateFormat class by passing your desired date format as a string to the constructor.
val dateFormat = SimpleDateFormat("dd/MM/yyyy")
val date = Date() // current date and time
  1. Call the format() method on your SimpleDateFormat object, passing in your Date object as a parameter.
val formattedDate = dateFormat.format(date)

Here are some additional examples:

// Format a timestamp to a string date val timestamp = 1629360000000 // 2021-08-19T00:00:00Z val date = Date(timestamp) val dateFormat = SimpleDateFormat("dd/MM/yyyy") val formattedDate = dateFormat.format(date) // "19/08/2021" // Format a string date to a different format val dateString = "19/08/2021" val dateFormat = SimpleDateFormat("dd/MM/yyyy") val date = dateFormat.parse(dateString) val newDateFormat = SimpleDateFormat("yyyy-MM-dd") val formattedDate = newDateFormat.format(date) // "2021-08-19"

That’s it! With these steps, you can easily format dates in Kotlin using the SimpleDateFormat class.

Читайте также:  Call oracle functions java

Method 2: Using the DateTimeFormatter Class

To format a date in Kotlin using the DateTimeFormatter class, you can follow these steps:

  1. Create a LocalDateTime object with the desired date and time.
  2. Define the pattern for the date format you want to use.
  3. Create a DateTimeFormatter object using the pattern.
  4. Format the LocalDateTime object using the DateTimeFormatter object.

Here is an example code that formats a date in the format «dd/MM/yyyy HH:mm:ss»:

import java.time.LocalDateTime import java.time.format.DateTimeFormatter fun formatDate(date: LocalDateTime): String  val pattern = "dd/MM/yyyy HH:mm:ss" val formatter = DateTimeFormatter.ofPattern(pattern) return date.format(formatter) > // Example usage val now = LocalDateTime.now() val formattedDate = formatDate(now) println(formattedDate) // Output: "25/08/2021 14:30:45"

In the above code, the formatDate function takes a LocalDateTime object as input and returns a formatted string using the DateTimeFormatter class.

You can customize the date format by changing the pattern variable to your desired format. For example, to format the date as «yyyy-MM-dd», you can change the pattern to «yyyy-MM-dd» .

Method 3: Using the Date class

To format a date in Kotlin using the Date class, you can use the SimpleDateFormat class. Here’s an example:

import java.text.SimpleDateFormat import java.util.Date fun formatDate(date: Date, format: String): String  val formatter = SimpleDateFormat(format) return formatter.format(date) > // Usage: val date = Date() val formattedDate = formatDate(date, "dd/MM/yyyy") println(formattedDate) // Output: 12/09/2021

In the example above, we define a function formatDate that takes a Date object and a format string as arguments, and returns a formatted date string. The SimpleDateFormat class is used to format the date according to the specified format.

The format string can contain various placeholders to represent different parts of the date, such as dd for day of the month, MM for month, yyyy for year, HH for hour, mm for minute, ss for second, and so on.

Here are some examples of format strings and their corresponding output:

val date = Date() formatDate(date, "dd/MM/yyyy") // Output: 12/09/2021 formatDate(date, "yyyy-MM-dd") // Output: 2021-09-12 formatDate(date, "EEE, MMM d, ''yy") // Output: Sun, Sep 12, '21 formatDate(date, "h:mm a") // Output: 10:30 PM

Note that the SimpleDateFormat class is not thread-safe, so it’s recommended to create a new instance for each thread or synchronize access to a shared instance.

Method 4: Using the Calendar class

To format a date in Kotlin using the Calendar class, you can follow these steps:

val calendar = Calendar.getInstance() calendar.timeInMillis = timestampInMillis
val dateFormat = SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.getDefault())
val formattedDate = dateFormat.format(calendar.time)

Here is the complete code example:

val calendar = Calendar.getInstance() calendar.timeInMillis = timestampInMillis val dateFormat = SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.getDefault()) val formattedDate = dateFormat.format(calendar.time)

In this example, timestampInMillis is the timestamp in milliseconds that you want to format. The dateFormat variable defines the format of the output date, which in this case is «dd/MM/yyyy HH:mm:ss». The Locale.getDefault() method is used to get the default locale of the device.

This code will output the formatted date as a string in the format «dd/MM/yyyy HH:mm:ss».

Note that the Calendar class is a bit outdated and there are newer and more efficient ways to format dates in Kotlin, such as using the Java 8 DateTime API or the Kotlin DateTime library.

Источник

How To Format Date Time In Kotlin

Kotlin is a programming language that allows you to write Android apps and program “happier”. Chances are if you are developing a mobile app for Android-based phones, tablets and watch you’ll need to learn Kotlin. Date Time Formatting in Kotlin is based on the SimpleDateFormat class and also the DateTimeFormatter class which was added in API level 26. This not at all different from SimpleDateFormat class that is used in Java 7 and the DateTimeFormatter class that is used in Java 8.

Patterns

If you are using an API level less than 26, please visit our Java7 Patterns Documentation.

If you are using an API level 26 or greater, please visit our Java 8 Patterns Documentation.

Kotlin Date Time Formatting Examples

For Kotlin API levels less than 26, here is a Kotlin SimpleDateFormat Example:

String pattern = "yyyy-MM-dd"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); String date = simpleDateFormat.format(new Date()); System.out.println(date);

Kotlin API Levels 26 or greater, here is a DateTimeFormatter Example:

import java.time.LocalDateTime import java.time.format.DateTimeFormatter fun main(args: ArrayString>)  val current = LocalDateTime.now() val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS") val formatted = current.format(formatter) println("Current Date and Time is: $formatted") >
Current Date and Time is: 2018-12-10 12:24:36.012

Источник

How To Format Date in Kotlin — All in One Solution

Are you worrying? How to format timestamp to String date? here you can find the complete solution in one place.

How To Format Date in Kotlin - All in One Solution

Here we have created a generic Method that you can use where ever you require.

public fun getDateFormattedFromTimeStamp(timestamp: Long, format: String): String

Usage: Time Stamp To Simple String Date Format

getDateFormattedFromTimeStamp(Calendar.getInstance().timeInMillis, "yyyy, MMM dd") output: // 2022, Sep 03

An explanation for other Date Formats

Year:

yyyy ” → 4-digit Year (eg. 2022 )
yy ” → 2-digit Year (eg. 22 )

Month:

MM ” → 2-digit Month (eg. 01 )
MMM ” → 3- character Month (eg. Jan )
MMMM ” → Full characters Month (eg. January )

Day:

dd ” or “ d ” → Day in a month (eg. 19 )

DD ” or “ D ” → Day in Year (eg. 262 )

val timestamp = 1663584353488 DateUtil.getDateFormattedFromTimeStamp(timestamp, "yyyy-MMM-dd") // 2022-Sep-19 DateUtil.getDateFormattedFromTimeStamp(timestamp, "yyyy, MMM dd") // 2022, Sep 19 DateUtil.getDateFormattedFromTimeStamp(timestamp, "yyyy/MMM/dd") // 2022/Sep/19 DateUtil.getDateFormattedFromTimeStamp(timestamp, "yyyy/MM/dd") // 2022/09/19 DateUtil.getDateFormattedFromTimeStamp(timestamp, "dd MMM, yy") // 19 Sep, 22 DateUtil.getDateFormattedFromTimeStamp(timestamp, "dd, MMM yy") // 19, Sep 22 DateUtil.getDateFormattedFromTimeStamp(timestamp, "dd, MMM yyyy") // 19, Sep 2022 DateUtil.getDateFormattedFromTimeStamp(timestamp, "dd MMM, yyyy") // 19 Sep, 2022 DateUtil.getDateFormattedFromTimeStamp(timestamp, "dd MM, yyyy") // 19 09, 2022 DateUtil.getDateFormattedFromTimeStamp(timestamp, "DD MM, yyyy") // 262 09, 2022 DateUtil.getDateFormattedFromTimeStamp(timestamp, "dd MMMM, yyyy") // 19 September, 2022

Источник

Оцените статью